使用sql查询结果填充datagridview
我正在尝试提供查询结果,但我一直在获取空白数据网格。 这就像数据本身不可见
这是我的代码:
private void Employee_Report_Load(object sender, EventArgs e) { string select = "SELECT * FROM tblEmployee"; Connection c = new Connection(); SqlDataAdapter dataAdapter = new SqlDataAdapter(select, c.con); //c.con is the connection string SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter); DataTable table = new DataTable(); table.Locale = System.Globalization.CultureInfo.InvariantCulture; dataAdapter.Fill(table); bindingSource1.DataSource = table; dataGridView1.ReadOnly = true; dataGridView1.DataSource = bindingSource1; }
这段代码出了什么问题?
这是你的代码修复。 接下来忘记bindingsource
var select = "SELECT * FROM tblEmployee"; var c = new SqlConnection(yourConnectionString); // Your Connection String here var dataAdapter = new SqlDataAdapter(select, c); var commandBuilder = new SqlCommandBuilder(dataAdapter); var ds = new DataSet(); dataAdapter.Fill(ds); dataGridView1.ReadOnly = true; dataGridView1.DataSource = ds.Tables[0];
String strConnection = Properties.Settings.Default.BooksConnectionString; SqlConnection con = new SqlConnection(strConnection); SqlCommand sqlCmd = new SqlCommand(); sqlCmd.Connection = con; sqlCmd.CommandType = CommandType.Text; sqlCmd.CommandText = "Select * from titles"; SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd); DataTable dtRecord = new DataTable(); sqlDataAdap.Fill(dtRecord); dataGridView1.DataSource = dtRecord;
你不需要bindingSource1
只需设置dataGridView1.DataSource = table;
尝试将DataGridView
绑定到DataTable
的DefaultView
:
dataGridView1.DataSource = table.DefaultView;
如果将数据源设置为添加到表单但未使用的数据集,则可能会获得空白数据网格。 如果您是基于上述代码以编程方式设置dataSource,请将此项设置为“无”。
您可以尝试此示例,并始终检查您的连接字符串 ,您可以将此示例与或使用out bindingsource,您可以将数据加载到datagridview。
private void Employee_Report_Load(object sender, EventArgs e) { var table = new DataTable(); var connection = "ConnectionString"; using (var con = new SqlConnection { ConnectionString = connection }) { using (var command = new SqlCommand { Connection = con }) { if (con.State == ConnectionState.Open) { con.Close(); } con.Open(); try { command.CommandText = @"SELECT * FROM tblEmployee"; table.Load(command.ExecuteReader()); bindingSource1.DataSource = table; dataGridView1.ReadOnly = true; dataGridView1.DataSource = bindingSource1; } catch(SqlException ex) { MessageBox.Show(ex.Message + " sql query error."); } } } }
您必须将属性表添加到DataGridView数据源
dataGridView1.DataSource = table.Tables[0];