简体   繁体   English

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

[英]How to show data in datagridview without using database

I want to show data in datagridview without using Database. 我想在不使用数据库的情况下在datagridview中显示数据。 In my UI there are 3 fields in which I inserted values and want to show them in data grid view when I execute the program it is not giving any error nor showing any values in datagridview. 在我的UI中,有3个字段,我在其中插入了值,并希望在执行程序时在数据网格视图中显示它们,它没有给出任何错误,也没有在datagridview中显示任何值。

图片

   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;
    }
    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
        }

You're almost there, but you need to do is add the new row to the DataTable : 您快到了,但是您需要做的是新行添加DataTable

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

Note that there is no constructor for DataRow but the DataTable.NewRow() call only uses the table layout as a template for the columns in the new row; 请注意,没有DataRow构造函数,但是DataTable.NewRow()调用仅将表布局用作新行中列的模板 it doesn't actually add it to the table. 它实际上并没有将其添加到表中。

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

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