Reputation: 103
i'm making ASP.net application and i want to have some kind of table there. I tried using Grindview, but when i try to add second new row (from code), the second row replaces first row.
here is code:
DataTable dt = new DataTable();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("thing", typeof(string));
dt.Columns.Add("thing2", typeof(string));
}
DataRow NewRow = dt.NewRow();
NewRow[0] = label1.Text;
NewRow[1] = label2.Text;
dt.Rows.Add(NewRow);
GridView1.DataSource = dt;
GridView1.DataBind();
I'm expecting Gridview with 2 rows and button which gives you new row with every click.
Upvotes: 4
Views: 15343
Reputation: 3316
if you have your front hand HTML asp.net code that define your gridview's style (here's an exemple) :
<asp:GridView ID="grvModel" runat="server" AlternatingRowStyle-BackColor="#eeeeee" BackColor="#aaccff" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:Button id="btnDel" CommandName="Delete" OnClientClick="btnDel_click" runat="server"Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate>
<asp:TextBox runat="server" ID="lblWrite" Text='write here' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then all you have to do is create a List<>
of object and bind it to your gridView, if you want to add somthing, just add to the list and bind it again (hers's an exemple) :
List<aClass> classList;
protected void BindFirstTime(object sender, EventArgs e)
{
classList= new List<aClass>();
classList.Add(new aClass("one"));
classList.Add(new aClass("two"));
Grv.DataSource = classList;
Grv.DataBind();
}
protected void AddObject(object sender, EventArgs e)
{
classList.Add(new aClass("three or more !"));
Grv.DataSource = classList;
Grv.DataBind();
}
This is the simple way for me, hope it helps.
Upvotes: 1
Reputation: 8592
You can add rows using a loop, where you create the row, add the content and then add the row to the datatable.
DataTable dt = new DataTable();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("thing", typeof(string));
dt.Columns.Add("thing2", typeof(string));
}
for(int i = 0; i < 3; i++)
{
DataRow dr = dt.NewRow();
dr[0] = "foo";
dr[1] = "bar";
dt.Rows.Add(dr);
}
Then bind the datatable to your GridView:
GridView1.DataSource = dt;
GridViewl.DataBind();
Upvotes: 1
Reputation:
I dont know what you exactly asking or trying to do but this might help
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("nameofcolumn1", typeof(string));
dt.Columns.Add("nameofcolumn2", typeof(string));
dt.Columns.Add("nameofcolumn3", typeof(string));
}
DataRow NewRow = dt.NewRow();
NewRow[0] = value1;
NewRow[ 1] = value2;
dt.Rows.Add(NewRow);
GridView1.DataSource = dt;
GridViewl.DataBind();
}
visit this link also Add row datagridview at every button click
Upvotes: 1