Обновить значения CheckBoxList из GridView и сохранить в базе данных
У меня есть анкета студента, в которой хранится информация студента. Форма выглядит так
Ниже приведен код. ПОЖАЛУЙСТА, подскажите, как обновить несколько флажков через Checkboxlist
<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:Label ID="Label6" runat="server" onCheckedChanged="onChackedChange" Text='<%# Eval("SUbjects") %>'></asp:Label>
</ItemTemplate>
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int studentid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());//Get Each Row unique value from DataKeyNames
string studentname = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1")).Text;//get TextBox Value in EditItemTemplet that row is clicked
string studentage = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2")).Text;
string studentdepartment = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropDownList1")).Text;
string studentgender = ((RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("RadioButtonList1")).Text;
CheckBoxList studentsubjects = ((CheckBoxList)GridView1.Rows[e.RowIndex].FindControl("CheckBoxList1"));
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("@name ", studentname);
cmd.Parameters.AddWithValue("@age ", int.Parse(studentage));
cmd.Parameters.AddWithValue("@department ", studentdepartment);
cmd.Parameters.AddWithValue("@gender ", studentgender);
cmd.Parameters.AddWithValue("@subjects ", studentsubjects);
}
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;// no row in edit mode
FillGrid();
conn.Close();
}
CREATE PROCEDURE [dbo].[StudentUpdate]
(
@student_id int,
@name varchar(50),
@age int,
@gender nvarchar(50),
@department nvarchar(50),
@subjects nvarchar(50)
)
AS UPDATE tblStudents set
NAME=@name,
AGE=@age,
DEPARTMENT=@department,
GENDER=@gender,
SUbjects=@subjects
where Student_ID=@student_id
protected void btnSave_Click(object sender, EventArgs e)
{
String gender;
if (rdBtnMale.Checked)
gender = rdBtnMale.Text;
else
gender = rdBtnFemale.Text;
string subject = "";
if (cboxPhysics.Checked)
{
subject = cboxPhysics.Text;
}
if (cboxChemistry.Checked)
{
if (subject != "")
{ subject = subject + ","; }
subject = subject + cboxChemistry.Text;
}
if (cboxBiology.Checked)
{
if (subject != "")
{ subject = subject + ","; }
subject = subject + cboxBiology.Text;
}
В этом изображении я применил изменения, но у меня есть это предупреждение.
2 ответа
Попробуй это:
.Aspx код:
<EditItemTemplate>
<asp:Label ID="Label1" Visible="false" runat="server" Text='<%# Eval("SUbjects") %>'></asp:Label>
<asp:CheckBoxList ID="CheckBoxList1" runat="server" SelectMethod="Multi" 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:Label ID="Label6" runat="server" onCheckedChanged="onChackedChange" Text='<%# Eval("SUbjects") %>'></asp:Label>
</ItemTemplate>
Код.CS:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow || (e.Row.RowState & DataControlRowState.Edit) > 0)
{
CheckBoxList chklist = ((CheckBoxList)e.Row.FindControl("CheckBoxList1"));
string subjects = ((Label)e.Row.FindControl("Label1")).Text;
string[] subjectslist = subjects.Split(',');
foreach (string item in subjectslist)
{
if (item == "Physics")
chklist.Items.FindByText("Physics").Selected = true;
else if (item == "Chemistry")
chklist.Items.FindByText("Chemistry").Selected = true;
else
chklist.Items.FindByText("Biology").Selected = true;
}
}
}
Примечание: не забудьте добавить OnRowDataBound
событие в GrindView <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" >
Вы должны зациклить все ListItems в CheckBoxList. С тем, что вы делаете сейчас, вы получаете только первый отмеченный элемент в списке, а не все.
//create a list to store all the subjects
List<string> studentsubjects = new List<string>();
//find the control in the GridView and cast it back to a CheckBoxList
CheckBoxList subjects = GridView1.Rows[e.RowIndex].FindControl("CheckBoxList1") as CheckBoxList;
//loop all the items and see if they are checked
foreach (ListItem item in subjects.Items)
{
if (item.Selected)
{
//add the checked value to the list
studentsubjects.Add(item.Text);
}
}
//display results
Label1.Text = string.Join(",", studentsubjects);