C# 从 GridViewRow ASP.NET 获取项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11694835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:52:29  来源:igfitidea点击:

Get Item from GridViewRow ASP.NET

c#asp.netgridview

提问by JsGarneau

I have a GridView which I Bind a DataSource to it from a SQL Database, the grid has a column with a checkbox in it so I can "select" a few Item in it (Rows actually). What I want here is to do some updates on the Item in each selected rows, but after some search I can't find how to access the Item in a Row, I though DataItem would work, but it's giving me a Null.

我有一个 GridView,我从 SQL 数据库将数据源绑定到它,网格有一个带有复选框的列,因此我可以“选择”其中的一些项目(实际上是行)。我想要在这里对每个选定行中的 Item 进行一些更新,但经过一些搜索后,我找不到如何访问 Row 中的 Item,我虽然 DataItem 可以工作,但它给了我一个 Null。

Edit:To make it short, I have a GridView which is built from a DataSource, so basically, each rows represent an Object, when I have a checkbox checked in one of the rows, I want to be able to grab the Object related to that Row, what is the easiest way to achieve that?

编辑:简而言之,我有一个从数据源构建的 GridView,所以基本上,每一行都代表一个对象,当我在其中一行中选中一个复选框时,我希望能够获取与那行,实现这一目标的最简单方法是什么?

The DataBinding on Page_Load:

Page_Load 上的数据绑定:

  if (!Page.IsPostBack)
    {
        gvUnusedAccessories.DataSource = currentContext.Items.OfType<Accessory>().Where(ac => ac.Item_Parent_Id == ((PhoneLine)currentItem).Parent.Item_Id);
        gvUnusedAccessories.AutoGenerateColumns = false;
        gvUnusedAccessories.DataBind();
    }
  if (!Page.IsPostBack)
    {
        gvUnusedAccessories.DataSource = currentContext.Items.OfType<Accessory>().Where(ac => ac.Item_Parent_Id == ((PhoneLine)currentItem).Parent.Item_Id);
        gvUnusedAccessories.AutoGenerateColumns = false;
        gvUnusedAccessories.DataBind();
    }

The event when I press the Update Button, It actually browse the rows and if the row has a checked box it's gonna do the update:

当我按下更新按钮时的事件,它实际上浏览行,如果行有一个复选框,它会进行更新:

protected void btnAddToMobile_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in gvUnusedAccessories.Rows)
    {
        if(((CheckBox)row.FindControl("chkSelect")).Checked)
        {
            ((Accessory)row.DataItem).PhoneLine_Id = currentItem.Item_Id;
        }
    }
}
protected void btnAddToMobile_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in gvUnusedAccessories.Rows)
    {
        if(((CheckBox)row.FindControl("chkSelect")).Checked)
        {
            ((Accessory)row.DataItem).PhoneLine_Id = currentItem.Item_Id;
        }
    }
}

And here's my GridView in the .aspx :

这是我在 .aspx 中的 GridView :

 <asp:GridView ID="gvUnusedAccessories" runat="server">
    <Columns>
        <asp:CommandField ShowSelectButton="True" />
        <asp:TemplateField HeaderText="Select">
            <ItemTemplate >
                <asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="True"/>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="Item_Id" HeaderText="ID" ReadOnly="True"/>
        <asp:BoundField DataField="Item_Name" HeaderText="Name" ReadOnly="True"/>  
        <asp:BoundField DataField="AccessoryModel" HeaderText="Modèle" ReadOnly="True"/>
        <asp:BoundField DataField="AccessoryBrand" HeaderText="Marque" ReadOnly="True"/>
    </Columns>
</asp:GridView>

Any hint on how to access the Object contained inside a Row? I know I could actually get the ID and then do a SQL request to my DB, but it seems to be a bit heavy and there must be a better solution.

关于如何访问包含在行中的对象的任何提示?我知道我实际上可以获取 ID,然后向我的数据库发出 SQL 请求,但这似乎有点重,必须有更好的解决方案。

采纳答案by Justin

Unless you're storing the DataSource in ViewState or session once the databinding is done you lose the data source. The DataItem will always be null unless you do this. Because of this I often find myself storing the data source in view state. Of course this means your page size is going to get bigger. The other option as you stated is to requery the data source with some sort of primary key. Depending on your needs I can't say which option is better. I tend to lean towards view state rather than a second DB call since that can be an expensive call to make

除非您在数据绑定完成后将 DataSource 存储在 ViewState 或 session 中,否则您将丢失数据源。除非您这样做,否则 DataItem 将始终为空。因此,我经常发现自己将数据源存储在视图状态中。当然,这意味着您的页面大小会变大。您所说的另一个选项是使用某种主键重新查询数据源。根据您的需要,我不能说哪个选项更好。我倾向于倾向于视图状态而不是第二个数据库调用,因为这可能是一个昂贵的调用

回答by HatSoft

Given that you have the AutoPostBackset to true on your asp:checkboxyou must update the row as you set the checkbox

鉴于您已将其AutoPostBack设置为 true,您asp:checkbox必须在设置复选框时更新该行

So I would suggest you you set event OnCheckedChanged="chkStatus_OnCheckedChanged"on asp:checkboxcalled chkSelectand then you can only update the selected row and don't have to iterate over the enitre grid.

所以我建议你OnCheckedChanged="chkStatus_OnCheckedChanged"asp:checkbox调用时设置事件chkSelect,然后你只能更新选定的行而不必遍历整个网格。

Here is an example how you can get the row items of the selected checkbox

这是一个如何获取所选复选框的行项目的示例

public void chkStatus_OnCheckedChanged(object sender, EventArgs e)
{
    CheckBox chkStatus = (CheckBox)sender;

    //now grab the row that you want to update
    GridViewRow row = (GridViewRow)chkStatus.NamingContainer;


    string cid = row.Cells[1].Text;
    bool status = chkStatus.Checked;

    //now you can do you sql update here
}