简体   繁体   English

如何在C#中向数据网格视图添加数据源

[英]How to add data source to Data Grid View in C#

In Windows Form Application I have two text boxes and 1 button and 1 Data Grid View. 在Windows窗体应用程序中,我有两个文本框和一个按钮和一个数据网格视图。

I am trying that on Button Click to show data in dataGridView on the basis of numbers given in Text Boxes 我正在尝试按钮单击以根据文本框中给出的数字在dataGridView中显示数据

I am not getting any error and I can't see any data in data grid view. 我没有收到任何错误,我在数据网格视图中看不到任何数据。

Here is my code: 这是我的代码:

private void Button1_Click(object sender, EventArgs e)
{

 SqlDataAdapter da_for_Branch;
 DataSet ds_forBranch = new DataSet();

 SqlConnection con;

con = new SqlConnection("Data Source=Test ;Initial Catalog=combit_cRM_Solution3;Integrated Security=True"); 

da_for_Branche = new SqlDataAdapter("SELECT Distinct(BusinessSectorID),Description_DE " +     
                                    " FROM BusinessSector5 " +
                                    " WHERE BusinessSectorID>= '"+ TxtBoxFrom.Text + "' " +      
                                    " AND BusinessSectorID<='" + TxtBoxTo.Text + "' " +
                                    " ORDER BY BusinessSectorID ", con);


da_for_Branche.Fill(ds_forBranches);

dataGridView1.DataSource = ds_forBranches;

}

You can't directly bind the Dataset as a data source to the grid. 您无法直接将数据集绑定为网格的数据源。 You can only bind table in a dataset. 您只能绑定数据集中的表。 In your cause you should bind the table in index 0. 在您的原因中,您应该绑定索引0中的表。

//Wrong
dataGridView1.DataSource = ds_forBranches;

//Right
dataGridView1.DataSource = ds_forBranches.Tables[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM