Inside the GridView SelectedIndexChanged event handler, the TextBoxes
outside GridView will be populated using the data fetched from the
GridView’s Selected Row.
HTML Markup
The HTML Markup consists of an ASP.Net
GridView and TextBoxes which will be used to display the data from the
Selected Row. For the GridView, I have specified the OnSelectedIndexChanged event handler.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
runat="server" AutoGenerateColumns="false" OnSelectedIndexChanged = "OnSelectedIndexChanged">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" Text='<%# Eval("Country") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Select" ID="lnkSelect" runat="server" CommandName="Select" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<table cellpadding="0" cellspacing="0">
<tr>
<td style="width: 100px">
Id
</td>
<td>
<asp:TextBox ID="txtId" runat="server" />
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
Name
</td>
<td>
<asp:TextBox ID="txtName" runat="server" />
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
Country
</td>
<td>
<asp:TextBox ID="txtCountry" runat="server" />
</td>
</tr>
</table>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
Binding the GridView control
I have created a dynamic DataTable with some dummy data and it has been bind to the GridView control in Page Load event.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country",typeof(string)) });
dt.Rows.Add(1, "Rama devi","India");
dt.Rows.Add(2, "Jason steve", "America");
dt.Rows.Add(3, "Rajitha Ganesh", "India");
dt.Rows.Add(4, "Kshatriya Dev", "Australia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Display GridView Selected Row data in TextBox outside GridView in ASP.Net using the SelectedIndexChanged event
Inside the SelectedIndexChanged
event handler of the GridView control, the values from the BoundField
and TemplateField columns are extracted and displayed in the respective
TextBoxes placed outside the GridView control.
C#
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
txtId.Text = row.Cells[0].Text;
txtName.Text = row.Cells[1].Text;
txtCountry.Text = (row.FindControl("lblCountry") as Label).Text;
}
ID
|
Name
|
Country
|
|
1
|
Rama
devi
|
India
|
Select
|
2
|
Jason
Steve
|
America
|
Select
|
3
|
Rajitha
Ganesh
|
India
|
Select
|
4
|
Kshatriya
Dev
|
Australia
|
Select
|
No comments:
Post a Comment