Pages

20 Aug 2013

Example of gridview rowcommand on Button Click

One of the most used controls in my projects is Gridview. Therefore, I thought of writing a tip which has been used in my projects frequently.

Gridview displays the value of a data source in a table. Here, I am going to give an example of using an event called "RowCommand". The RowCommand is raised when a button, LinkButton or ImageButton is clicked in the Gridview Control.


The HTML part of the gridview is:

asp:GridView ID="gridMembersList"
AutoGenerateColumns="False" GridLines="None"
            runat="server"
            onrowcommand="gridMembersList_RowCommand">
        <Columns>
        <asp:TemplateField HeaderText="User Name">
        <ItemTemplate>
            <asp:Literal ID="ltrlName" runat="server"
            Text='<%# Eval("Name") %>'></asp:Literal>
            <asp:Literal ID="ltrlSlno" runat="server" Visible="False"
                Text='<%# Eval("Id") %>'></asp:Literal>
        </ItemTemplate>
        </asp:TemplateField>
     
        <asp:TemplateField HeaderText="View More">
        <ItemTemplate>
            <asp:Button ID="btnViewmore"
            CommandArgument="<%# ((GridViewRow) Container).RowIndex %>
            " CommandName="More" runat="server" Text="View More" />
        </ItemTemplate>
        </asp:TemplateField>
        </Columns>

        </asp:GridView>


In the HTML part , I have binded the values which have to be displayed on the page.

And in the code behind, I have used an XML to load the data to the gridview. When the button is clicked, the event verifies for the command name and command argument.

And, then, I have just alerted the name of the user in this example. Changes can be made according to the requirement.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string pathofxml = Server.MapPath("xml/MemberDetails.xml");
            DataSet ds = new DataSet();
            ds.ReadXml(pathofxml);
            gridMembersList.DataSource = ds;
            gridMembersList.DataBind();
        }
    }


protected void gridMembersList_RowCommand(object sender, GridViewCommandEventArgs e)
   {
        if (e.CommandName == "More")
        {
            int index = Convert.ToInt32(e.CommandArgument.ToString());
            Literal ltrlslno = (Literal)gridMembersList.Rows[index].FindControl("ltrlSlno");
            Literal ltrlName = (Literal)gridMembersList.Rows[index].FindControl("ltrlName");
            ScriptManager.RegisterStartupScript(this, this.GetType(),
            "Message", "alert('" + ltrlName.Text+ "');", true);
        }
    }


I hope this will be helpful for the beginner.

No comments:

Post a Comment