在复选框选择上,使用列表视图字段更新数据库

On Checkbox selection, update database using listview fields

我正在使用列表视图显示数据库中的各种 columns/rows。这些列之一是 "id" 并且对用户隐藏。另一列是用户可以单击以 "pick up a task" 的复选框。

<asp:ListView ID="listViewDataSource" ConvertEmptyStringToNull="true"  ItemPlaceholderID="itemPlaceholder" runat="server" DataKeyNames="id,intFrmID" SelectedIndex="0">

然后在 ItemTemplate 中:

<tr runat="server">
<td class="hidden">
   <asp:Label ID="id" runat="server" Text='<%#Eval("id") %>' /> 
</td>
<td>
  <asp:CheckBox ID="check" runat="server" OnCheckedChanged="check1_CheckedChanged" AutoPostBack="True" Checked='<%# (bool)Eval("bitIsPickedUp") %>' />
  <asp:Label ID="CheckLabel" runat="server" Text='<%#Eval("bitIsPickedUp") %>' />
</td>

当有人点击该复选框时,我想在数据库中创建一条新记录。为此,我需要获取隐藏的 "id" 字段并将其传递给添加记录的函数。

    protected void check1_CheckedChanged(object sender, EventArgs e)
    {
        //in here, I want to get the id, which I should be able to use listViewDataSource.SelectedDataKey but the datakey has one value and it's not correct, makes me think it's being cached somehow?
        var datakey = listViewDataSource.SelectedDataKey;
        CheckBox chk = (CheckBox)item.FindControl("bitIsPickedUp");


    }

我对 Web 表单和 ListView 的使用不是很熟悉,因此不胜感激。

除了您可能会在 PostBacks 上丢失 SelectedItem 这一事实之外,您的代码还有一些问题。因此,我将在这里添加一些内容....

protected void check1_CheckedChanged(object sender, EventArgs e) {
    //this is null...
    ListViewItem item = (ListViewItem)listViewDataSource.SelectedValue;

    if (item == null) {
        if (listViewDataSource.Items.Count > 0) {
            item = (ListViewItem)listViewDataSource.Items[0];
        }
    }

    if (item != null) {
        //this returns a checkbox = true value and upon expanding has lots of data that's not super helpful, except maybe the clientID which has the row number
        CheckBox myCheckBox = (CheckBox)sender;

        // add NULL CHECK

        //FindControl doesn't seem to find anything, gets null
        CheckBox chk = (CheckBox)item.FindControl("bitIsPickedUp");

        // add NULL CHECK

        if (chk.Checked) {
            string intId = ((Label)item.FindControl("id")).Text;
            bool success = Int32.TryParse(intId, out int id);
            if (success) {
                GoQuote.InsertIntoGoList(id, 16073);
            }
        }
    } else {
        // log error -- execute additonal logic
    }