如何在不使用数据库的情况下在datagridview中显示数据

时间:2016-05-31 15:38:46

标签: c# winforms datagridview

我想在不使用数据库的情况下在datagridview中显示数据。在我的UI中有3个字段,我在其中插入值并希望在执行程序时在数据网格视图中显示它,它没有给出任何错误,也没有在datagridview中显示任何值。

Picture

   private void Submit_Click(object sender, EventArgs e)
    {
        DataRow dr = dt.NewRow();
        dr[0] = txtBox1.Text;
        dr[1] = txtBox2.Text;
        dr[2] = txtBox3.Text;
        dataGridView1.DataSource = dt;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        dt = new DataTable();
        DataColumn dc1 = new DataColumn("Name");
        DataColumn dc2 = new DataColumn("Email");
        DataColumn dc3 = new DataColumn("ConatctNumber");
        dt.Columns.Add(dc1);
        dt.Columns.Add(dc2);
        dt.Columns.Add(dc3);
        dt.Rows.Add(dc1);
        DataRow dr = dt.NewRow();
        dataGridView1.DataSource = dt;
    }

2 个答案:

答案 0 :(得分:3)

    DataTable dt = new DataTable();
    private void Form1_Load(object sender, EventArgs e)
       {    
         dt.Columns.Add ("Name");
         dt.Columns.Add ("Email");
         dt.Columns.Add ("ConatctNumber");        
        // dt.Rows.Add(dc1); dc1 is a column not a row   >>>
        // DataRow dr = dt.NewRow();  not necessary
         dataGridView1.DataSource = dt;
       }
     private void Submit_Click(object sender, EventArgs e)
        {
            DataRow dr = dt.NewRow();
            dr[0] = txtBox1.Text;
            dr[1] = txtBox2.Text;
            dr[2] = txtBox3.Text;
             dt.rows.add(dr);   //You forgot to add new row in your datatable
          //  dataGridView1.DataSource = dt; is already definedin loadForm
        }

答案 1 :(得分:0)

你几乎就在那里,但你需要做的是添加新行到DataTable

    DataRow dr = dt.NewRow();
    dr[0] = txtBox1.Text;
    dr[1] = txtBox2.Text;
    dr[2] = txtBox3.Text;
    dt.Rows.Add(dr);             // <<< ====
    dataGridView1.DataSource = dt;

请注意,DataRow没有构造函数,但DataTable.NewRow()调用仅将表格布局用作新行中列的模板;它实际上并没有将它添加到表中。