i need help getting the row selection into the text box's when the user clicks the edit button in the grid view, i have the event and will show you the code i have tried. I am running on visual studio 2013 and sql server 2012.
txtname.Text = gridview.Rows[gridview.SelectedIndex].Cells[1].Text;
txtname.Text = gridview.Rows[gridview.SelectedRow].Cells[1].Text;
[screens] http://imgur.com/WCsvnLB,cLdMeQN
Rather than gridview.SelectedIndex
you should have an event arg and grab it's index. From the docs :
protected void TaskGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
TaskGridView.EditIndex = e.NewEditIndex;
//Bind data to the GridView control.
BindData();
}
So yours would be:
protected void gridView_RowEditing(object sender, GridViewEditEventArgs e)
{
txtname.Text = gridview.Rows[e.NewEditIndex].Cells[1].Text;
}
Firstly create a Gridview using code below
<asp:GridView ID="GV" runat="server" AutoGenerateColumns="false" OnRowEditing="GV_RowEditing" DataKeyNames="id">
<Columns>
<asp:TemplateField HeaderText="Username">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("Column1")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Password">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#Eval("Column2")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="edit" OnClick="LinkButton1_Click" >Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
then generate the row editing event of gridview and in that write this code
string id = GV.DataKeys[e.NewEditIndex].Value.ToString();
string select = "select * from tblLogin where id ='"+Convert.ToInt16(id)+"'";
ds = gs.select(select);
if (ds.Tables[0].Rows.Count > 0)
{
lblName.Text= ds.Tables[0].Rows[0]["Column1"].ToString();
lblPass.Text=ds.Tables[0].Rows[0]["Column2"].ToString();
}
hope this will help
So i used a combination of both your answers and came up with this one which works fine:
int id = Convert.ToInt32(gridview.DataKeys[e.NewEditIndex].Value);
txtid.Text = id.ToString();
txtname.Text = gridview.Rows[id].Cells[3].Text;
txtadd.Text = gridview.Rows[id].Cells[4].Text;
txtcountry.Text = gridview.Rows[id].Cells[5].Text;
txtcity.Text = gridview.Rows[id].Cells[6].Text;
txtpin.Text = gridview.Rows[id].Cells[7].Text;
Let me know what you think and if this is bad coding let me know aswell.
Thanx
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.