ViewState with example in asp.net C#

Showing posts with label get primary key in gridview. Show all posts
Showing posts with label get primary key in gridview. Show all posts

Monday, February 21, 2011

get primary key in gridview

*********RowCommand_event of Gridview*************
Step1: Add the gridview in your .aspx page.
<div>
    <asp:GridView ID="GridView1" runat="server"  AutoGenerateColumns="false"          
             DataKeyNames="EmpID"onrowcommand="GridView1_RowCommand">
          <Columns>
            <asp:BoundField DataField="EMPID" HeaderText="EmployeeID" />
         <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
            <asp:BoundField DataField="LastName" HeaderText="LastName" />
            <asp:BoundField DataField="Address" HeaderText="Address" />
            <asp:BoundField DataField="Mobile" HeaderText="Mobile" />
            <asp:TemplateField>
            <ItemTemplate>
            <asp:Button ID="btnSelect" runat="server" Text="Select" CommandName="Select" CommandArgument='<%# Eval("Mobile") %>' />
            </ItemTemplate>
            </asp:TemplateField>
          </Columns>
        </asp:GridView>


        <asp:Label ID="lblMessage" runat="server"></asp:Label>   
    
        <asp:TextBox ID="txtMobile" runat="server"></asp:TextBox>
    </div>


step 2:- your .aspx.cs page.


NOTE:- this is my connection string which is using in below coding you can use your own to modify it in your web.config file.
My connectiion string is.
"

<connectionStrings>
    <add name="mycon" connectionString="data source=SHIVAMGUPTA; initial catalog=operation; integrated security=true;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

"
**********************your code behind part.*********************

public partial class SelectGridColumn : System.Web.UI.Page
{


SqlConnection con;
    protected void Page_Load(object sender, EventArgs e)
    {
        string conection;
        conection = System.Configuration.ConfigurationManager.ConnectionStrings["mycon"].ConnectionString.ToString();
        con = new SqlConnection(conection);
        if (!IsPostBack)
        {
            FillGrid();
        }
    }




    protected void FillGrid()
    {
        SqlCommand cmd = new SqlCommand("select * from employee", con);
        con.Open();
        GridView1.DataSource = cmd.ExecuteReader();
        GridView1.DataBind();
        con.Close();
    }


    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            txtMobile.Text = Convert.ToString(e.CommandArgument);
            lblMessage.Text = "this the mobile no of selected row!";
        }
    }


}