Gridview行重复C# [英] Gridview row duplication C#

查看:82
本文介绍了Gridview行重复C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,



我有一个网页,允许学生注册课程,如果学生选择已经学过的课程,我想显示错误信息之前和已经在gridview中。



代码中的所有东西都运行正常,但是当我使用这个循环

Hello,

I have a webpage that allow the student to register courses and I want to display an error message if the student choose a course that has been taken before and already in the gridview.

Everything in the code is working fine,but when I use this loop

for (int i = 0; i < GridView1.Rows.Count;i++)

代码仅检查第一行。





如何让for循环遍历gridview的所有行



我尝试过:



the code check the firt row only.


How can I make the for loop go through the all rows of gridview

What I have tried:

protected void Button1_Click(object sender, EventArgs e)
        {

            for (int i = 0; i < GridView1.Rows.Count;i++)
            {

             if (GridView1.Rows[i].Cells[4].Text == DropDownList2.SelectedValue.ToString())
                {

                    //display error message.
                }
                else
                {
                    string stid = Label1.Text;
                    string coursecode = DropDownList2.SelectedValue.ToString();
                    string docid = lblDocID.Text;
                    string semester = lblSemester.Text;
                    string sessiondays = lblSessionDays.Text;
                    string days = lblDays.Text;
                    string timing = lblTiming.Text;
                    string startid = lblStartTime.Text;
                    string endtime = lblEndTime.Text;
                    string roomid = lblRoomID.Text;


                    SqlConnection ConnString = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
              String query = "insert into Registration values (@St_ID, @Semester, @CourseCode, @Doc_ID, @SessionDays, @Days, @Timing, @StartTime, @EndTime, @RoomID)";
                    SqlCommand cmd = new SqlCommand(query);

                    cmd.Connection = ConnString;
                    cmd.Parameters.AddWithValue("@St_ID", stid);
                    cmd.Parameters.AddWithValue("@Semester", semester);
                    cmd.Parameters.AddWithValue("@CourseCode", coursecode);
                    cmd.Parameters.AddWithValue("@Doc_ID", docid);
                    cmd.Parameters.AddWithValue("@SessionDays", sessiondays);
                    cmd.Parameters.AddWithValue("@Days", days);
                    cmd.Parameters.AddWithValue("@Timing", timing);
                    cmd.Parameters.AddWithValue("@StartTime", startid);
                    cmd.Parameters.AddWithValue("@EndTime", endtime);
                    cmd.Parameters.AddWithValue("@RoomID", roomid);
                    ConnString.Open();
                    cmd.ExecuteNonQuery();
                    ConnString.Close();

                    Response.Redirect("~/StudentAddDropCourse.aspx");

                }
            }
     }

推荐答案

你可能会发现它有些冗长的解决方案并且有重构的空间,但你可以尝试下面的解决方案 -



You may find it some lengthy solution and have room for refactoring to but you can try below solution -

protected void Button1_Click(object sender, EventArgs e)
{
    var dataSource = GridView1.DataSource as DataTable;

    //Get all cources
    List<string> cources = new List<string>();
    foreach (DataRow row in dataSource.Rows)
    {
        //put your column details here
        cources.Add(row.ItemArray[1].ToString());
    }

    //Check if course already selected and avail in grid
    string SelectedCource = cources.Distinct().FirstOrDefault(m => m.Equals("<USERSELECTEDCOURCE>"));

    if(!String.IsNullOrEmpty(SelectedCource))
    {
        //error
    }
    else
    {
        //whatever you want to do to new selected cource
    }
}


在我看来,你的代码每次都在添加数据循环中的比较失败,但由于你没有打破循环,你继续迭代。对于显示错误消息后的if语句,您应该中断以退出for循环。你不应该使用else语句,除非你已经查看了所有的行,这意味着你已经遍历并且没有进入if语句并且中断。所以将else更改为'else if(i == GridView1.Rows.Count - 1)'。



It looks to me like your code is adding data every time the comparison fails inside the loop, but since you don't break the loop you continue to iterate through. For the if statement after you display the error message you should break to exit the for loop. You shouldn't do the else statement unless you've looked at all of the rows already, meaning you iterated through and didn't go into the if statement and break. So change the else to something like 'else if (i == GridView1.Rows.Count - 1)'.

//condition changed to <= to account for empty grid, count = 0
for (int i = 0; i <= GridView1.Rows.Count;i++)
{
//Check row count first, if it is 0 then the other contidtions are not checked, go to else if.
    if ((GridView1.Rows.Count != 0) && 
        (GridView1.Rows[i].Cells[4].Text == DropDownList2.SelectedValue.ToString()))
    {
        //display error message.
        break;
    }
//If the grid is empty, add data and break out of the loop. If end of the rows and no match found, add data and break out of the loop.
    else if ((GridView1.Rows.Count == 0) || (i == GridView1.Rows.Count - 1))
    {
        //your stuff here.
        break;  // added break so i still less than count when we exit
    }
}


这篇关于Gridview行重复C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆