简体   繁体   中英

C#: How to add details to a DataTable and display it on a DataGridView without storing in the database

I want to store details to a DataTable when a button is pressed and display it on a DataGridView when the add button is pressed. How can I achieve this. Please help me. Thanks a lot.

I tried this code. But I need a way to bind it with the datagrid.

        DataRow dr;
        DataTable dt=new DataTable();

        dt.Columns.Add("LoginId", typeof(int));

        dt.Columns.Add("UserFirstName", typeof(string));
        dt.Columns.Add("LastName", typeof(string));

        dt.Columns.Add("Password", typeof(string));
        dt.Columns.Add("EmailId", typeof(string));

        dt.Columns.Add("Role", typeof(string));
        dt.Columns.Add("Description", typeof(string));

        dr = dt.NewRow();

Here's the way to bind DataTable on DataGridView

myDataGrid.DataSource = myDataTable;
myDataGrid.DataBind();

You can add columns to the datatable as you need, and then add rows, like this:

    DataTable dt = new DataTable();
    int value = 0;
    private void Form1_Load(object sender, EventArgs e)
    {
        dataGridView1.AutoGenerateColumns = true;

        dt.Columns.AddRange(new DataColumn[]
            {
                new DataColumn("column1", typeof(string)),
                new DataColumn("column2", typeof(int)),
            });
    }

    private void button1_Click(object sender, EventArgs e)
    {

        dt.Rows.Add("str value", value++);
        dataGridView1.DataSource = dt;
    }

In your given code you are not adding newly created row in data table, you can add row in data table like this

    dr = dt.NewRow();

    dt.Rows.Add(dr);

    GridView1.DataSource = dt;
    GridView1.DataBind();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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