How to add a row dynamically in editable grid in asp.net using C#. In my website I need to take input from user for number of rows required and then generate an editable grid view. Please send me code to solve this.
Thank You.
How to add a row dynamically in editable grid in asp.net using C#. In my website I need to take input from user for number of rows required and then generate an editable grid view. Please send me code to solve this.
Thank You.
I have solved my question and got the correct answer through self study. I want to share it..
First add a DropDownList and a GridView in your form and in DropDownList add some choices for user regarding number of rows they want to add at run time, in my website I have added four numbers : 1,2,3,4; And the code behind is:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
int x = Convert.ToInt32(DropDownList1.SelectedItem.ToString()); // Number of rows
DataTable dt = new DataTable();
for (int i = 0; i < x; i++)
{
DataRow row1 = dt.NewRow();
dt.Rows.Add(row1);
}
for (int i = 0; i < x; i++)
{
DataRow row1 = dt.NewRow(); //Adding rows
dt.Rows.Add(row1);
}
//Bind the datatable with the GridView.
GridView1.DataSource = dt;
GridView1.DataBind();
}
You have to build a datasource which you can bind to the Grid. For example you can use a DataTable
or List<myObject>
to store your data. Then use this as datasource and the GridView become show datas from you datasource. If you want to add/delete datas just add/delete the object from your datasource. Example code:
public class Test{
public int Id {get; private set;}
public string Bez {get; private set;}
public Test(int id, string bez)
{
this.Id = id;
this.Bez = bez;
}
}
Create Datasource with objects:
List<Test> allTests = new List<Test>();
allTests.add(new Test(1, "Test"));
allTests.add(new Test(2, "Test2"));
myGrid.DataSource = allTests;
Now you can just work with the list. The Grid will need Refresh maybe to show edits. If you edit data in your Grid this will directly effect your datasource objects.
If this is not what you are searching for, clarify you question please.