我已经使用以下代码在组合框中显示我的SQL数据库表的名称。如何通过从组合框中选择任何表来填充DataGridView
现在我希望当我从组合框中单击任何这些表名时,我的DGV将填充该表的内容。
private void Form1_Load(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "TABLE_NAME";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
然后我用下面的代码填充我的DGV,但它不工作;请帮忙。
private void PopulateGridView()
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strconnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + comboBox1.SelectedText;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
PopulateGridView(comboBox1.SelectedValue.ToString());
}
}
您是否尝试调试您的代码?说“它不工作”是什么意思?你有没有收到任何错误信息或什么? – 2013-03-13 06:46:00
为什么当该方法是无参数时,用参数调用'PopulateGridView'方法? – 2013-03-13 06:48:04
我hav调试我的代码...组合框显示我的sql数据库中的表名...但我的dgv没有填充表中的内容我从组合框中选择..plzz帮助 – 2013-03-13 06:50:04