We can bind the DataGridView in C#.net with the help of following code:
SqlConnection vConn = new SqlConnection("Server=localhost; database=rohit; user id=sa; pwd=***");
vConn.Open();
String vQuery = textBox1.Text;
SqlDataAdapter vAdap = new SqlDataAdapter(vQuery, vConn);
DataSet vDs = new DataSet();
vAdap.Fill(vDs, "Emp");
dataGridView1.DataBindings.Clear();
DataTable vDt = vDs.Tables["Emp"];
dataGridView1.DataSource = vDs;
dataGridView1.DataMember = "Emp";
vConn.Close();
SqlConnection vConn = new SqlConnection("Server=localhost; database=rohit; user id=sa; pwd=***");
vConn.Open();
String vQuery = textBox1.Text;
SqlDataAdapter vAdap = new SqlDataAdapter(vQuery, vConn);
DataSet vDs = new DataSet();
vAdap.Fill(vDs, "Emp");
dataGridView1.DataBindings.Clear();
DataTable vDt = vDs.Tables["Emp"];
dataGridView1.DataSource = vDs;
dataGridView1.DataMember = "Emp";
vConn.Close();
//BIND
THE LISTBOX WITH THE COLUMN FROM DATABASE.
SqlConnection
vConn = new SqlConnection("Server=localhost; database=rohit; user id=sa;
pwd=***");
vConn.Open();
String vQuery =
comboBox1.SelectedItem.ToString();
SqlDataAdapter vAdap = new SqlDataAdapter("Select
ename,sal, job from emp", vConn);
DataSet vDs = new DataSet();
vAdap.Fill(vDs, "Emp");
vConn.Close();
DataTable vDt = vDs.Tables["Emp"];
listBox1.DataBindings.Clear();
listBox1.DataSource = vDt;
switch
(vQuery)
{
case
"Ename":
listBox1.DisplayMember = "Ename";
break;
case
"Salary":
listBox1.DisplayMember = "Sal";
break;
case
"Job":
listBox1.DisplayMember = "job";
break;
}
Happy Coding. Keep on trying.
Comments