Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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++)
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:

C#
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");

                }
            }
     }
Posted
Updated 21-Apr-17 6:47am
v3
Comments
Angelo L 20-Apr-17 19:13pm    
Using the debugger, have you verified the strings you are comparing in the if statement, GridView1.Rows[i].Cells[4].Text and DropDownList2.SelectedValue.ToString()?
R.M49 20-Apr-17 19:17pm    
yes, the problem is that the for loop checks only the first row, it doesn't go through the all rows.
Angelo L 20-Apr-17 20:25pm    
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)'.
R.M49 21-Apr-17 4:19am    
wooow, it is working now, can you please write it as a soultion so I can accept it.
Angelo L 21-Apr-17 12:48pm    
Glad to have helped.

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
    }
}
 
Share this answer
 
v2
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
    }
}
 
Share this answer
 
v3
Comments
R.M49 24-Apr-17 3:34am    
What if the table binded to the gridview is empty ?? it will be no rows in the gridview so how will the loop will work ?
Angelo L 24-Apr-17 19:14pm    
I updated the solution. Check my comments on what I did.
R.M49 25-Apr-17 17:54pm    
Thank youu.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900