1
我試圖從GridView更新CheckBoxList。但是我有上面提到的錯誤。更新CheckBoxList時不存在映射對象類型System.Collections.Generic.List
我也有其他的領域,如姓名,性別,年齡,部門在這個形式的代碼,但我已經消除了無關的代碼,爲你們輕鬆。
以下爲GridView的
代碼<div>
<asp:GridView ID="GridView1" class="table table-striped table-bordered" runat="server" Width="603px" DataKeyNames="Student_ID" OnRowEditing="GridView1_RowEditing" OnRowDeleting="GridView1_RowDeleting" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowUpdating="GridView1_RowUpdating" AutoGenerateColumns="False" HorizontalAlign="Center" > <%--OnRowDataBound="GridView1_RowDataBound"--%>
<Columns>
<asp:TemplateField HeaderText="Student ID">
<EditItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# Eval("Student_ID") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Student_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subjects">
<EditItemTemplate>
<asp:CheckBoxList ID="CheckBoxList1" runat="server" RepeatDirection="Horizontal" SelectedValue='<%# Eval("SUbjects") %>' > <%--OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged--%>
<asp:ListItem Value="Physics">Physics</asp:ListItem>
<asp:ListItem Value="Chemistry">Chemistry</asp:ListItem>
<asp:ListItem Value="Biology">Biology</asp:ListItem>
</asp:CheckBoxList >
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBoxList ID="CheckBoxList2" runat="server" RepeatDirection="Horizontal" SelectedValue='<%# Eval("SUbjects") %>' > <%--OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged--%>
<asp:ListItem Value="Physics">Physics</asp:ListItem>
<asp:ListItem Value="Chemistry">Chemistry</asp:ListItem>
<asp:ListItem Value="Biology">Biology</asp:ListItem>
</asp:CheckBoxList >
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True"/>
<asp:CommandField HeaderText="Edit" ShowEditButton="True" ValidationGroup="update" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
下面是更新
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int studentid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
CheckBoxList subjects = ((CheckBoxList)GridView1.Rows[e.RowIndex].FindControl("CheckBoxList1")) as CheckBoxList;
List <string> studentsubjects = new List <string>();
foreach (ListItem item in subjects.Items)
{
if (item.Selected)
{
studentsubjects.Add(item.Text);
}
}
SqlConnection conn = new SqlConnection("Data Source=WINCTRL-0938L38; Database=dbUni; Integrated Security=true");
conn.Open();
SqlCommand cmd = new SqlCommand("StudentUpdate", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@student_id ", studentid);
cmd.Parameters.AddWithValue("@subjects ", studentsubjects);
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
FillGrid();
conn.Close();
}
爲GridView的行代碼更新複選框列表