0

我在 formview 对象中放置了一个复选框列表。我想将复选框列表的结果存储并加载到实体框架的表中。

我使用 DataSourceID、DataTextField 和 DataValueField 属性为 cbl 填充了来自具有 2 列的表的值和标签,但我似乎找不到如何将 cbl 绑定到实体框架对象以存储检查的值当表单视图处于“编辑”模式时。

任何帮助将不胜感激。谢谢!

<asp:FormView ID="formView1" runat="server" DataSourceID="Ods1" 
        Height="203px" Width="495px" 
        onpageindexchanging="formView1_PageIndexChanging">
<EditItemTemplate>
    <asp:CheckBoxList ID="cblProducts" runat="server" RepeatColumns="3" 
                Width="782px" DataSourceID="SqlDataSource1" DataTextField="ProductName" 
                DataValueField="ProductCode">
    </asp:CheckBoxList>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:ApplicationServices %>" 
                SelectCommand="SELECT [ProductCode], [ProductName] FROM [Products]">
    </asp:SqlDataSource>
</EditItemTemplate>
</asp:FormView>
    <asp:ObjectDataSource ID="Ods1" runat="server" 
        DataObjectTypeName="WebApplication1.EDM.Emp" DeleteMethod="DeleteEmp" 
        InsertMethod="CreateNewEmp" OldValuesParameterFormatString="original_{0}" 
        SelectMethod="GetEmpByEmpId" TypeName="WebApplication1.EDM.EmpLogic" 
        UpdateMethod="UpdateEmp" OnSelecting="Ods1_Selecting">
        <SelectParameters>
            <asp:RouteParameter Name="EmpId" RouteKey="EmpId" Type="String" />
        </SelectParameters>
    </asp:ObjectDataSource>
4

2 回答 2

0

您需要执行以下操作;

foreach (ListItem chk in cblProducts.Items)
{
    string productId= chk.Value;
    if (IsProductAvailable(productId) // this method will basically goes to database and return true of false
        chk.Selected = true;
    else
        chk.Selected = false;
}


private void IsProductAvailable(string productId)
{
        string query = "SELECT [ProductId] FROM [Product] ";
        query += "WHERE [ProductId] = @ProductId";
        DbCommand comm = new DbCommand();
        comm.CommandText = query;

        DbParameter param = comm.CreateParameter();
        param.ParameterName = "@ProductId";
        param.Value = productId;
        comm.Parameters.Add(param);

        DataTable table = comm.ExecuteCommand();
        if (table.Rows.Count > 0)
        {
            return true;
        }
        else
            return false;
}

请根据您的需要修改查询和参数。

于 2012-08-23T14:38:27.737 回答
0
<asp:FormView ID="formView1" runat="server" 
     OnItemUpdating="formView1_ItemUpdating" ...>

protected void formView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
   var cblProducts = formView1.FindControl("cblProducts") as CheckBoxList;

   foreach (ListItem item in cblProducts.Items)
   {
       if (item.Selected)
       {
           // Check if item.Value is not in the db for this employee, if so add it
       }
       else
       {
           // Check if item.Value is in the db for this employee, if so delete it
       }
   }

   // save
}
于 2012-08-23T14:25:48.830 回答