已添加具有相同键的项 向数据库添加网格值时出现问题
本文关键字:添加 网格 数据库 问题 | 更新日期: 2023-09-27 17:56:20
在下面的代码中,我想将网格视图值插入到数据库中。当我尝试插入值时,它会抛出错误"已添加具有相同键的项目"。仅将第一行添加到数据库中,不会添加剩余行。请帮助我解决问题。
protected void btnSave_Click(object sender, EventArgs e)
{ string Check=string.Empty;
string BranchID = dpbranch.SelectedValue;
string ClassID = dpClassName.SelectedValue;
string SectionID = dpsection.SelectedValue;
TestSchool.SchoolBusinessLyr.SchoolBizClient Attendance = new TestSchool.SchoolBusinessLyr.SchoolBizClient();
System.Collections.Generic.Dictionary<string, string> AssignStudentAttendance = new System.Collections.Generic.Dictionary<string, string>();
DataSet ds = new DataSet();
foreach (GridViewRow row in gdstudentattendance.Rows)
{
String cellText = row.Cells[0].Text;
String RegisterNo = row.Cells[2].Text;
int rowIndex = 0;
for (int i = 0; i < gdstudentattendance.Rows.Count; i++)
{
//extract the TextBox values
CheckBox StudentAttendance = (CheckBox)gdstudentattendance.Rows[i].Cells[i].FindControl("chkattendance");
if(StudentAttendance.Checked==true)
{
Check="true";
}
else
{
Check="false";
}
AssignStudentAttendance.Add("BranchID", BranchID);
AssignStudentAttendance.Add("ClassID", ClassID);
AssignStudentAttendance.Add("SectionID", SectionID);
AssignStudentAttendance.Add("StudentID", cellText.ToString());
AssignStudentAttendance.Add("RegisterNo", RegisterNo.ToString());
AssignStudentAttendance.Add("Attendance", Check.ToString());
Attendance.InsertStudentAttendance(AssignStudentAttendance);
}
}
}
您应该为每一行创建新的字典。喜欢:
protected void btnSave_Click(object sender, EventArgs e)
{ string Check=string.Empty;
string BranchID = dpbranch.SelectedValue;
string ClassID = dpClassName.SelectedValue;
string SectionID = dpsection.SelectedValue;
TestSchool.SchoolBusinessLyr.SchoolBizClient Attendance = new TestSchool.SchoolBusinessLyr.SchoolBizClient();
System.Collections.Generic.Dictionary<string, string> AssignStudentAttendance;
DataSet ds = new DataSet();
foreach (GridViewRow row in gdstudentattendance.Rows)
{
//Create new dictionary for each row
AssignStudentAttendance = new System.Collections.Generic.Dictionary<string, string>();
String cellText = row.Cells[0].Text;
String RegisterNo = row.Cells[2].Text;
int rowIndex = 0;
for (int i = 0; i < gdstudentattendance.Rows.Count; i++)
{
//extract the TextBox values
CheckBox StudentAttendance = (CheckBox)gdstudentattendance.Rows[i].Cells[i].FindControl("chkattendance");
if(StudentAttendance.Checked==true)
{
Check="true";
}
else
{
Check="false";
}
AssignStudentAttendance.Add("BranchID", BranchID);
AssignStudentAttendance.Add("ClassID", ClassID);
AssignStudentAttendance.Add("SectionID", SectionID);
AssignStudentAttendance.Add("StudentID", cellText.ToString());
AssignStudentAttendance.Add("RegisterNo", RegisterNo.ToString());
AssignStudentAttendance.Add("Attendance", Check.ToString());
Attendance.InsertStudentAttendance(AssignStudentAttendance);
}
}
}