gridview

时间:2018-04-07 11:27:12

标签: c# sql winforms

我创建了一个表单并添加了一个gridview,我正在尝试从SQL Server数据库中检索数据。当我运行我的代码时,我没有在gridview中显示任何错误或数据。请帮忙..

private void Form1_Load(object sender, EventArgs e)
{
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

    using (SqlConnection con = new SqlConnection(CS))
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from tblProductInventory", con);
        dataGridView1.DataSource = cmd.ExecuteReader();            
    }  
}

3 个答案:

答案 0 :(得分:0)

string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

SqlConnection conn = new SqlConnection(CS);
    conn.Open();
    string query = "Select * from tblProductInventory";

    SqlCommand cmd = new SqlCommand(query, conn);

    DataTable t1 = new DataTable();
    using (SqlDataAdapter a = new SqlDataAdapter(cmd))
    {
        a.Fill(t1);
    }

    dataGridView1.DataSource = t1;

答案 1 :(得分:0)

使用DataAdapter填充DataTable。

 private void Form1_Load(object sender, EventArgs e)
        {
            DataTable dataTable= new DataTable();
            string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(CS))
            {
              con.Open();
              SqlCommand cmd = new SqlCommand("Select * from tblProductInventory", con);               
              SqlDataAdapter adapter = new SqlDataAdapter(cmd);
              adapter.Fill(dataTable);                    
              dataGridView1.DataSource = dataTable;             
            }  
       }

答案 2 :(得分:0)

ExecuteReader方法从给定表(从数据库)读取数据,并为您构建DataReader

您无法使用command.ExecuteReader直接填充数据网格视图。您需要使用DataReaderDataTable

DataTable示例:

  DataTable dt = new DataTable()
  using (SqlDataAdapter ada = new SqlDataAdapter(cmd))
{
    ada.Fill(t1);
}
 MyDatagrid.Datasource = dt;

现在我永远不会建议使用DataTable,因为它既耗时又妨碍表现。请使用DataReader

DataReader示例:

''It is better to create a class to handle your data :)

  public class MyData
{
    private int age;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    private int id;

    public int Id
    {
        get { return id; }
        set { id = value; }
       } 
    }

  ''Ever heard of ArrayList...It's amazing :)

  ArrayList myarray= new ArrayList();

  '''Now let's fix the main issue :)

  SqlDataReader reader = command.ExecuteReader();
  while (reader.Read())
  {
  MyData data = new MyData();
  data.Id = (int)reader[0];
  data.Name = reader[1].ToString();
  data.Age = (int)reader[2];
  myArray.Add(data);
  }
  myDataGrid.DataSource = sequence;