How to get a dataset value - sql

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)

Related

How to query SQL to RichEditControl DevExpress?

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();

Syntax Error in FROM clause - SQL Fault

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.

SQL Count from specific Column in Database

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);
}
}

How to use SQL parameters with NpgsqlDataAdapter?

Is it possible to use parameters together with NpgsqlDataAdapter, as I can do with NpgsqlCommand:
string sql = "SELECT * FROM tbl_student WHERE name = #val";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
command.Parameters.AddWithValue("#val", name);
I have this code, which displays the information about the students i a gridview:
string sql = "SELECT * FROM tbl_student WHERE studentname = '" + name + "'";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
ds.Reset();
da.Fill(ds); // filling DataSet with result from NpgsqlDataAdapter
dt = ds.Tables[0]; // select select first column
GridView1.DataSource = dt; //connect grid to DataTable
GridView1.DataBind();
My question is: can I somehow use parameters (as in the example above) instead of using '" + name + "' in the SQL?
I have learned always to use parameters, is it also necessary when using NpgsqlDataAdapter?
Thank you.
I used to have the same question and this is what I came up with:
string sql = "SELECT * FROM tbl_student WHERE studentname = #param";
NpgsqlCommand command = new NpgsqlCommand(sql,conn);
command.Parameters.Add("#param", textBox_studentname.Text); //add the parameter into the sql command
DataTable dt = new DataTable();
//load the DataReader object of the command to the DataTable
dt.Load(NpgsqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection));
GridView1.DataSource = dt;
You could read this and this.

How to use the ID of an item after loading combobox from database.?

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