AL3MS AL3MS - 2 months ago 11
Vb.net Question

what is the command of select in grid view asp.net

I have a

GridView
called
gridview1


What I want is that if the user select or click on specific row some action will happen.

For example I want to get the value from that row and store it in a new variable.

How can I do it? I'm confused about what I should do to get the value?

protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
string stuId = ?
}

Answer
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    AutoGenerateColumns="false" OnSelectedIndexChanged = "OnSelectedIndexChanged">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
            <ItemTemplate>
                <asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:ButtonField Text="Select" CommandName="Select" ItemStyle-Width="150" />
    </Columns>
</asp:GridView>
<br />
<u>Selected Row Values: </u>
    <br />
<br />
<asp:Label ID="lblValues" runat="server" Text=""></asp:Label>

aspx.cs code

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
        dt.Rows.Add(1, "John Hammond", "United States");
        dt.Rows.Add(2, "Mudassar Khan", "India");
        dt.Rows.Add(3, "Suzanne Mathews", "France");
        dt.Rows.Add(4, "Robert Schidner", "Russia");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}

protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
    //Accessing BoundField Column
    string name = GridView1.SelectedRow.Cells[0].Text;

    //Accessing TemplateField Column controls
    string country = (GridView1.SelectedRow.FindControl("lblCountry") as Label).Text;

    lblValues.Text = "<b>Name:</b> " + name + " <b>Country:</b> " + country;
}

you simply copy and paste your issue is resolve.

Comments