在下面的代码中,我在网格中创建了动态文本框,我将值保存在数据库中。在我的情况下,gridview中只创建了两行,但在数据库中它保存了4行。请帮助我解决问题
TestSchool.SchoolBusinessLyr.SchoolBizClient Grade = new TestSchool.SchoolBusinessLyr.SchoolBizClient();
System.Collections.Generic.Dictionary<string, string> AssignGrade = new System.Collections.Generic.Dictionary<string, string>();
foreach (GridViewRow row in gdassignmark.Rows)
{
int rowIndex = 0;
for (int i = 0; i < gdassignmark.Rows.Count; i++)
{
//extract the TextBox values
TextBox Sa = (TextBox)gdassignmark.Rows[i].Cells[i].FindControl("txtsa");
TextBox fa = (TextBox)gdassignmark.Rows[i].Cells[i].FindControl("txtfa");
// var SubjectID = gdassignmark.DataKeys[rowIndex]["SubjectID"] as string;
String cellText = row.Cells[0].Text;
String cellText1 = row.Cells[2].Text;
if (cellText != string.Empty)
{
if (fa.Text == "0")
{
int faval = int.Parse(fa.Text);
int mark = (faval / 40) * 100;
string strmark = mark.ToString();
AssignGrade.Add("BranchID", dpbranch.SelectedValue);
AssignGrade.Add("Academicyear", dpacademicyear.SelectedValue);
AssignGrade.Add("ExamID", dpExamName.SelectedValue);
AssignGrade.Add("ClassID", dpClassName.SelectedValue);
AssignGrade.Add("SectionID", "1");
AssignGrade.Add("SubjectID", cellText.ToString());
AssignGrade.Add("StudentID", dpStudentName.SelectedValue);
AssignGrade.Add("FA", Sa.Text);
AssignGrade.Add("SA", "");
AssignGrade.Add("FAandSA", (strmark));
Grade.InsertStudentGrade(AssignGrade);
}}
答案 0 :(得分:0)
您正在循环两次。假设Rows [i] Cells [i]是正确的,您可以将代码更改为不循环遍历每行的所有行:
//foreach (GridViewRow row in gdassignmark.Rows)
//{
int rowIndex = 0;
for (int i = 0; i < gdassignmark.Rows.Count; i++)
{
GridViewRow row = gdassignmark.Rows[i]
//Do your stuff here
}
//}
答案 1 :(得分:0)
您正在遍历网格视图两次
删除外部foreach,以便您的代码看起来像这样
TestSchool.SchoolBusinessLyr.SchoolBizClient Grade
= new TestSchool.SchoolBusinessLyr.SchoolBizClient();
System.Collections.Generic.Dictionary<string, string> AssignGrade
= new System.Collections.Generic.Dictionary<string, string>();
for (int i = 0; i < gdassignmark.Rows.Count; i++)
{
//extract the TextBox values
TextBox Sa = (TextBox)gdassignmark.Rows[i].Cells[i].FindControl("txtsa");
TextBox fa = (TextBox)gdassignmark.Rows[i].Cells[i].FindControl("txtfa");
// var SubjectID = gdassignmark.DataKeys[rowIndex]["SubjectID"] as string;
String cellText = row.Cells[0].Text;
String cellText1 = row.Cells[2].Text;
if (cellText != string.Empty)
{
if (fa.Text == "0")
{
int faval = int.Parse(fa.Text);
int mark = (faval / 40) * 100;
string strmark = mark.ToString();
AssignGrade.Add("BranchID", dpbranch.SelectedValue);
AssignGrade.Add("Academicyear", dpacademicyear.SelectedValue);
AssignGrade.Add("ExamID", dpExamName.SelectedValue);
AssignGrade.Add("ClassID", dpClassName.SelectedValue);
AssignGrade.Add("SectionID", "1");
AssignGrade.Add("SubjectID", cellText.ToString());
AssignGrade.Add("StudentID", dpStudentName.SelectedValue);
AssignGrade.Add("FA", Sa.Text);
AssignGrade.Add("SA", "");
AssignGrade.Add("FAandSA", (strmark));
Grade.InsertStudentGrade(AssignGrade);
}
}