网格视图中的选择命令是什么?

本文关键字:命令 是什么 选择 视图 网格 | 更新日期: 2023-09-27 18:07:09

我有一个GridView叫做gridview1

我想要的是,如果用户选择或单击特定的行,一些操作将发生

例如,我想从该行获取值并将其存储在一个新变量中。

我该怎么做?我不知道该怎么做才能得到这个值?

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

网格视图中的选择命令是什么?

<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>
<<p> aspx.cs代码/strong>
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;
}

你只需复制粘贴你的问题就解决了

可以这样使用:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false" 
    OnRowCommand = "OnRowCommand">
 <Columns>    
 <asp:ButtonField CommandName = "ButtonField"  DataTextField = "StudID"
            ButtonType = "Button"/>
</Columns>
</asp:GridView>

protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
    int index = Convert.ToInt32(e.CommandArgument);
    GridViewRow gvRow = GridView1.Rows[index]; 
}