Showing posts with label add row for gv. Show all posts
Showing posts with label add row for gv. Show all posts

11 September 2012

How to get the current row in the grid view rowcommand event

GridViewRow row = ((LinkButton)e.CommandSource).NamingContainer as GridViewRow;

In RowDataBound for datakeys

GridView1.DataKeys[e.Row.RowIndex].Value.ToString()

((DataRowView)e.Row.DataItem)["mainid"].ToString()

30 September 2011

creating new row for a gridview dynamically

if (!IsPostBack)
{
getdata();
}
----------------------------
void getdata()
{
dalLogin dal = new dalLogin();
DataSet ds = new DataSet();
ds= dal.getdata();
ViewState["table"] = ds.Tables[0];
bindgrid();
}
void bindgrid()
{
GridView1.DataSource = (DataTable)ViewState["table"];
GridView1.DataBind();
}
-------------------------------
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[5].Attributes.Add("style", "display:none");
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
GridView1.Rows[i].Cells[5].Attributes.Add("style", "display:none");
}
}
-----------------------------------
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "newrow")
{
DataTable dt = (DataTable)ViewState["table"];
dt.Rows.Add(dt.NewRow());
ViewState["table"] = dt;
GridView1.EditIndex = GridView1.Rows.Count;
bindgrid();
Button btn = (Button)GridView1.Rows[GridView1.Rows.Count - 1].FindControl("Button1");
btn.Text = "save";
btn.CommandName = "sav";
}
else if (e.CommandName == "sav")
{
TextBox t1 = (TextBox)GridView1.Rows[GridView1.Rows.Count - 1].Cells[0].Controls[0];
TextBox t2 = (TextBox)GridView1.Rows[GridView1.Rows.Count - 1].Cells[1].Controls[0];
TextBox t3 = (TextBox)GridView1.Rows[GridView1.Rows.Count - 1].Cells[2].Controls[0];
TextBox t4 = (TextBox)GridView1.Rows[GridView1.Rows.Count - 1].Cells[3].Controls[0];
TextBox t5 = (TextBox)GridView1.Rows[GridView1.Rows.Count - 1].Cells[4].Controls[0];
DataTable dt = (DataTable)ViewState["table"];
dt.Rows.RemoveAt(GridView1.Rows.Count - 1);
DataRow dr = dt.NewRow();
dr[0] = t1.Text; dr[1] = t2.Text; dr[2] = t3.Text; dr[3] = t4.Text; dr[4] = t5.Text;
dt.Rows.Add(dr);
ViewState["table"] = dt;
GridView1.EditIndex = -1;
bindgrid();
Button btn = (Button)GridView1.Rows[GridView1.Rows.Count - 1].FindControl("Button1");
btn.Text = "new";
btn.CommandName = "newrow";
}
}