I have tried alot of changes from previous posts. Does anyone know what could be cause this?
(I know the code shouldn't be used from a security point of view but its a small local based system)
Con.Open();
oleDbCmd.Connection = Con;
OleDbDataReader rdr = null;
OleDbCommand cmd = new OleDbCommand("select * from Customers", Con);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Int32 intChech = Convert.ToInt32(cboCustomerID.Text);
if (intChech == (Int32)rdr.GetValue(0))
{
txtTitle.Text = (string)rdr.GetValue(1);
txtSurname.Text = (string)rdr.GetValue(2);
txtForename.Text = (string)rdr.GetValue(3);
txtAddress.Text = (string)rdr.GetValue(4);
txtTown.Text = (string)rdr.GetValue(5);
txtCounty.Text = (string)rdr.GetValue(6);
txtPostCode.Text = (string)rdr.GetValue(7);
txtTelephone.Text = (string)rdr.GetValue(8);
}
}
//PULL DATABASE INFORMATION FOR CAR INFO
string strSearch = Convert.ToString(cboCustomerID.Text);
string strSQL = #"select * from Hire if [Customer ID] = '";
OleDbDataAdapter dAdapter1 = new OleDbDataAdapter(strSQL, Con);
OleDbCommandBuilder cBuidler1 = new OleDbCommandBuilder(dAdapter1);
DataTable dataTable1 = new DataTable();
DataSet ds1 = new DataSet();
dAdapter1.Fill(dataTable1);
for (int i = 0; i < dataTable1.Rows.Count; i++)
{
dgHire1.Rows.Add(dataTable1.Rows[i][0], dataTable1.Rows[i][1], dataTable1.Rows[i][2],
dataTable1.Rows[i][3], dataTable1.Rows[i][4]);
}
}
You should use this code:
//PULL DATABASE INFORMATION FOR CAR INFO
string strSQL = #"select * from Hire where [Customer ID] = ?";
OleDbDataAdapter dAdapter1 = new OleDbDataAdapter(strSQL, Con);
dAdapter1.SelectCommand.Parameters.Add("[Customer ID]", cboCustomerID.Text);
OleDbCommandBuilder cBuidler1 = new OleDbCommandBuilder(dAdapter1);
Or if you don't want to use command parameters you can use this:
string strSQL = #"select * from Hire where [Customer ID] = '" + cboCustomerID.Text + "'";
OleDbDataAdapter dAdapter1 = new OleDbDataAdapter(strSQL, Con);
OleDbCommandBuilder cBuidler1 = new OleDbCommandBuilder(dAdapter1);
But this is bad practice.
Related
I want to fill data from SQL Server to RichEditControl.Text. I used this code but it doesn't work, my RichEditControl.Text has an empty string.
string connectionstring = "Data Source=ADMIN;Initial Catalog=Shoplacviet;Integrated Security=True";
SqlConnection conn = new SqlConnection(connectionstring);
conn.Open();
string query = "select * from so";
SqlCommand cmd = new SqlCommand(query, conn);
var reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
richEditControl1.Options.MailMerge.DataSource = dt;
richEditControl1.Options.MailMerge.ViewMergedData = true;
richEditControl1.Text = dt.ToString();
conn.Close();
I want to get a SQL Count of the number of records that pertain to my bundnum column and display it into my textblock. Any suggestions?
SqlConnection conn = new SqlConnection("db connection");
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "SELECT COUNT(*) FROM dbo.tablename WHERE bundnum = 'values' ";
conn.Open();
int returnValue = (int)comm.ExecuteScalar();
txtNumber.Text = returnValue.ToString();
Using Google, I found this helpful link and after some modification:
Int32 newCount = 0;
string newValue = "something";
string sql =
"SELECT COUNT(*) FROM dbo.tablename WHERE bundnum = '#myValue'";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#myValue", SqlDbType.VarChar);
cmd.Parameters["#myValue"].Value = newValue;
try
{
conn.Open();
newCount = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
SqlConnection con = new SqlConnection(#"server=RSTT2; database = Project ; User Id=sa; Password=PeaTeaCee5#");
con.Open();
string strCmd = "select ID,Name from Employee";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
cbSupportID.DataSource = ds;
cbSupportID.DisplayMember = "Name";
cbSupportID.ValueMember = "ID";
cbSupportID.Enabled = true;
cmd.ExecuteNonQuery();
con.Close();
now i want use the id of items in my form to process..Plzz tell me the best solution with code.
now you simply retrieve your selected combobox ID value using
cbSupportID.SelectedValue
eg.
If cbSupportID.SelectedIndex <> -1 Then
textBox1.Text = cbSupportID.SelectedValue.ToString()
End If
You can also access other useful properties like SelectedIndex (starting from 0...) or SelectedItem.
check here: http://msdn.microsoft.com/en-US/library/system.windows.forms.listcontrol.selectedvalue(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2
I got a stored procedure in SQL Server I created some inner joins and now how will I populate my datagrid using that stored procedure.
Here is my code that is not working
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
cmd.CommandText = "OfficeEquipmentProfile"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlconn
sqlconn.Open()
sAdapter = New SqlDataAdapter(cmd)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet
sAdapter.Fill(sDs, "tblOfficeEquipmentProfile")
sAdapter.Fill(sDs, "tblDepartment")
sAdapter.Fill(sDs, "tblLocation")
sAdapter.Fill(sDs, "tblOfficeEquipmentCategory")
sAdapter.Fill(sDs, "tblApplication")
sAdapter.Fill(sDs, "tblApplicationLicense")
sAdapter.Fill(sDs, "tblEquipmentApplication")
sAdapter.Fill(sDs, "tblOfficeEquipmentBrand")
sAdapter.Fill(sDs, "tblOfficeEquipmentModel")
sAdapter.Fill(sDs, "tblOfficeEquipmentServiceOrder")
sAdapter.Fill(sDs, "tblOfficeEquipmentPMplan")
sTable = sDs.Tables("tblOfficeEquipmentProfile")
sTable = sDs.Tables("tblDepartment")
sTable = sDs.Tables("tblLocation")
sTable = sDs.Tables("tblOfficeEquipmentCategory")
sTable = sDs.Tables("tblApplication")
sTable = sDs.Tables("tblApplicationLicense")
sTable = sDs.Tables("tblEquipmentApplication")
sTable = sDs.Tables("tblOfficeEquipmentBrand")
sTable = sDs.Tables("tblOfficeEquipmentServiceOrder")
sTable = sDs.Tables("tblOfficeEquipmentPMplan")
DataGrid1.DataSource = sDs.Tables("tblOfficeEquipmentProfile, tblDepartment, tblLocation, tblOfficeEquipmentCategory, tblApplication,tblApplicationLicense, tblEquipmentApplication, tblOfficeEquipmentBrand, tblOfficeEquipmentServiceOrder,tblEquipmentPMplan")
DataGrid1.ReadOnly = True
'Button1.Enabled = False
'DataGrid1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
reader = cmd.ExecuteReader()
sqlconn.Close()
I just want to display records from the database
As you are returning columns from different tables and not multiple tables then you just need this code.
Dim Command As SqlCommand = New SqlCommand()
Command.Connection = Connection
Command.CommandText = "OfficeEquipmentProfile"
Command.CommandType = CommandType.StoredProcedure
Dim sAdapter As SqlDataAdapter = New SqlDataAdapter(Command)
Dim DataSet As DataSet = New DataSet(Command.CommandText)
sAdapter.Fill(DataSet)
DataGrid1.DataSource = DataSet.Tables(0)
Try with this code
Dim cmd As New SqlCommand
cmd.CommandText = "OfficeEquipmentProfile"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlconn
sqlconn.Open()
sAdapter = New SqlDataAdapter(cmd)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet
sAdapter.Fill(sDs)
DataGrid1.DataSource = sDs
The storedprocedure return one or more tables, but you don't need to call a Fill for each table. One is enough. Then assign the whole Dataset to the Datasource or, if you return more than one table and need a specific table
DataGrid1.DataSource = sDs
DataGrid1.DataMember = "tablename"
Try
If con.State = ConnectionState.Open Then con.Close()
con.Open()
Dim dset As New DataSet
Dim dbind As New BindingSource
Dim strquery As String
strquery = "SELECT prod_code, prod_no, prod_suffix, prod_lvl, customer, model, family, company_code, company_name, company_address, running_no, template_code FROM products_tbl WHERE template_code = 'n'and company_code = 'YTPL' and prod_no = '" & txt_product.Text & "' and prod_suffix = '" & txt_suffix.Text & "' and prod_lvl = '" & txt_level.Text & "'"
Dim adap As New SqlDataAdapter(strquery, con)
dset = New DataSet
adap.Fill(dset)
dbind.DataSource = dset.Tables(0)
dg.DataSource = dbind
Catch ex As Exception
MsgBox("Trace No 3: System Error or Data Error!" + Chr(13) + ex.Message + Chr(13) + "Please Contact Your System Administrator!", vbInformation, "Message")
End Try
New to VB.Net,
How to insert or select the dataset value.
cmd = New SqlCommand("Select * from table1", con)
ada = New SqlDataAdapter(cmd)
ds = New DataSet
ada.Fill(ds)
cmd = New SqlCommand("Select * from '" & ds.Tables(0) & "' ", con)
mydatatable1.Load(dr3)
It was showing the error in '" & ds.Tables(0) & "', I want to get the dataset value
Need VB.Net Code Help
You have a reasonable idea right up until you get to the point where you are trying to create a second SqlCommand. That is, once you do the Fill, you already have the data in a table. You wouldn't run another select - you've already done that. You'd just reference the table that you want to use in the dataset.
If you want a data table you would do something like this (for VB, see below):
SqlDataAdapter myAdapter = new SqlDataAdapter(CommandText, con);
DataSet myDataset = new DataSet();
myAdapter.Fill(myDataset, "Table"); // "Table" is just a name, it can be anything.
mydatatable1 = myDataset.Tables[0]; // Get the table
Now, if you don't need a DataTable, per se, but just want to read from the query, you'd use a SqlDataReader:
cmd = new SqlCommand(CommandText, con);
// One or more params
cmd.Parameters.AddWithValue("#paramName", Value);
SqlDataReader nwReader = cmd.ExecuteReader();
Then just read from the nwReader:
while (nwReader.Read())
{
string field1Val = (string)nwReader["FieldName"];
etc...
}
Update: I don't know VB but here is what I think it would look like:
cmd = New SqlCommand("Select * from table1", con)
ada = New SqlDataAdapter(cmd)
ds = New DataSet
ada.Fill(ds)
mydatatable1 = ds.Tables(0);
You may well be able to shorten this to get rid of the extra SqlCommand (assuming VB supports this SqlDataAdapater syntax like C#.
ada = New SqlDataAdapter("Select * from table1", con)
ds = New DataSet
ada.Fill(ds)
mydatatable1 = ds.Tables(0);
Good luck...
you can use Microsoft Enterprise Library for making easy this process. this library is a powerful library for working with datasets.
public async Task<ResponseStatusViewModel> GetAll()
{
var responseStatusViewModel = new ResponseStatusViewModel();
var connection = new SqlConnection(EmployeeConfig.EmployeeConnectionString);
var command = new SqlCommand("usp_GetAllEmployee", connection);
command.CommandType = CommandType.StoredProcedure;
try
{
await connection.OpenAsync();
var reader = await command.ExecuteReaderAsync();
var dataSet = new DataSet();
dataSet.Load(reader, LoadOption.OverwriteChanges, new string[] { "Employee" });
reader.Close();
reader.Dispose();
var employees = new List<EmployeeModel>();
if (dataSet.Tables.Count > 0 && dataSet.Tables["Employee"] != null)
{
var employeeTable = dataSet.Tables["Employee"];
for (int i = 0; i < employeeTable.Rows.Count; i++)
{
var employeeRow = employeeTable.Rows[i];
employees.Add(new EmployeeModel
{
EmployeeID = Convert.ToInt32(employeeRow["EmployeeID"]),
EmployeeName = Convert.ToString(employeeRow["EmployeeName"]),
Address = Convert.ToString(employeeRow["Address"]),
GrossSalary = Convert.ToDouble(employeeRow["GrossSalary"]),
PF = Convert.ToDouble(employeeRow["PF"]),
TotalSalary = Convert.ToDouble(employeeRow["TotalSalary"])
});
}
}
responseStatusViewModel.Data = employees;
command.Dispose();
connection.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return responseStatusViewModel;
}
I think what you are looking for is
cmd = New SqlCommand("Select * from '" & ds.Tables(0).TableName & "' ", con)
cmd = New SqlCommand("Select * from table1", con)
ada = New SqlDataAdapter(cmd)
ds = New DataSet
ada.Fill(ds)
cmd = New SqlCommand("Select * from '" & ds.Tables(0).TableName & "' ", con)
mydatatable1.Load(dr3)