Click here to Skip to main content
15,899,313 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to add some rows in datagridview (without binding) from 4 Textboxes. but I need first to check if it is already added, it yes then show a message, if not already added, then add the text value of the Textboxin the gridview. I am using VS 2008 with C# I search a lot of all available solutions but not working with me.

I tried to loop on the rows but I couldnt work.

C#
foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if ((string)row.Cells[0].Value == txtbx1.Text && ((string)row.Cells[1].Value == txtbx2.Text.ToString() && ((string)row.Cells[2].Value == txtbx3_new.Text.ToString() && ((string)row.Cells[3].Value == txtbx4.Text.ToString()))))
                    {
                        b_found = true;
                         MessageBox.Show("Test");
                         break;
                    }
                     
                }
                
                else
                {
                    dataGridView1.Rows.Add(new object[] { txtbx1.Text, txtbx2.Text, txtbx3.Text, txtbx4.Text, false });
                   
                }
Posted
Updated 14-Nov-14 2:53am
v2

1 solution

C#
private void button1_Click(object sender, EventArgs e)
        {
            bool entryFound = false;
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                object val1 = row.Cells[0].Value;
                object val2 = row.Cells[1].Value;
                object val3 = row.Cells[2].Value;
                object val4 = row.Cells[3].Value;
                if (val1 != null && val1.ToString() == textBox1.Text &&
                    val2 != null && val2.ToString() == textBox2.Text &&
                    val3 != null && val3.ToString() == textBox3.Text &&
                    val4 != null && val4.ToString() == textBox4.Text)
                {
                    MessageBox.Show("Entry already exist");
                    entryFound = true;
                    break;
                }
            }

            if (!entryFound)
            {
                dataGridView1.Rows.Add(textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text);
            }

        }
 
Share this answer
 
Comments
Muhammad Saqlain 14-Nov-14 9:23am    
good coding.

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