Add new rows to DataGridView on Button click using C# in Windows Forms Application

Last Reply 4 days ago By dharmendr

Posted 4 days ago

Hi! It's worked Get data from database by using function. DataGridView completed from database. Now I want click button and add free rows for insert new data.

Iddol named salaryb
1 Yakub 55
2 Firuz 100
3 Sadriddin

When I click button then after Sadriddin add new free rows.

Posted 4 days ago

Hi PRA,

Refer the below sample code. For binding you need to use DataTable or DataSet to bind. So that you can able to add new row. If you are binding with List then datagrid did not allow you to set the property to add new row.

C#

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    Grid.DataSource = GetData();
    Grid.AllowUserToAddRows = false;
}

public DataTable GetData()
{
    DataTable dt = new DataTable();
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[1].ConnectionString);
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "Select TOP 5 * from Customers";
    cmd.Connection = con;
    con.Open();
    try
    {
        dt.Load(cmd.ExecuteReader());
    }
    catch
    {

    }
    finally
    {
        con.Close();
    }

    return dt;
}

private void button1_Click(object sender, EventArgs e)
{
    DataTable dt = GetData();
    dt.Rows.Add(GetData().Rows.Count + 1, "", "");
    Grid.DataSource = dt;
    Grid.AllowUserToAddRows = false;            
}

 

I agree, here is the link: http://e-iceblue.com/free-api