It is common requirement when we work in a single page means when our input parameters and display records from database in a gridview and we have to get data from selected row to manipulate.
Table Design
Design View (Source code)
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="FrmGetGridViewValue.aspx.cs" Inherits="FrmGetGridViewValue" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<table class="style1">
<tr>
<td>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" />
<asp:BoundField DataField="name" HeaderText="Name" />
<asp:CommandField ShowSelectButton="True" HeaderText="CommandField"/>
<asp:TemplateField HeaderText="LinkButton">
<ItemTemplate>
<asp:LinkButton ID="LnkSelect" runat="server" CommandName="link">Select</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="ID"></asp:Label>
<asp:TextBox ID="txtid" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label2" runat="server" Text="Name"></asp:Label>
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</asp:Content>
C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class FrmGetGridViewValue : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
string x = "select * from st1";
da = new SqlDataAdapter(x,con);
ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
txtid.Text = GridView1.SelectedRow.Cells[0].Text;
txtname.Text = GridView1.SelectedRow.Cells[1].Text;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "link")
{
GridViewRow val = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
int RowIndex = val.RowIndex;
txtid.Text = GridView1.Rows[RowIndex].Cells[0].Text;
txtname.Text = GridView1.Rows[RowIndex].Cells[1].Text;
}
}
}
No comments:
Post a Comment