简体   繁体   中英

c# textbox to datagridview

I want to add the exact value of textbox into datagridview my problem is if i will add another item the last item I add will also change. Here is the print screen of sample problem..

1st try

在此处输入图片说明

2nd try

在此处输入图片说明

This is my code.

int n = dataGridView3.Rows.Add();

for (int j = 0; j < dataGridView3.RowCount; j++) 
{
    if (dataGridView3.Rows[j].Cells[1].Value != null && (textBox4.Text == dataGridView3.Rows[j].Cells[4].Value.ToString()))
    {
        MessageBox.Show("Item Already on List!");
        dataGridView3.Rows.Remove(dataGridView3.Rows[n]);
        return;
    }
    else 
    {
        dataGridView3.Rows[j].Cells[1].Value = textBox43.Text;
        dataGridView3.Rows[j].Cells[4].Value = textBox4.Text;
        dataGridView3.Rows[j].Cells[2].Value = DateTime.Now.ToShortDateString();
        dataGridView3.Rows[j].Cells[3].Value = dateTimePicker3.Text;            

        dataGridView3.FirstDisplayedScrollingRowIndex = n;
        dataGridView3.CurrentCell = dataGridView3.Rows[n].Cells[0];
        dataGridView3.Rows[n].Selected = true; 
    }
}

You are looping over the complete array and if it is not yet on the list it goes in to the else part of your if. In that block you assign the current entered values to your row, for every single row you already have.

To fix that I separated the Check for duplicates and the Add part more clearly.

Do notice that if you would have run this through the debugger and stepped on each line of your code (hitting F10 in Visual Studio) you would have spotted this bug easily. Have a look at the blog from Scott Guthrie (among others) http://weblogs.asp.net/scottgu/debugging-tips-with-visual-studio-2010

    // check if we already added that one
    for (int j = 0; j < dataGridView3.RowCount; j++) 
    {
        if (dataGridView3.Rows[j].Cells[1].Value != null && (textBox4.Text == dataGridView3.Rows[j].Cells[4].Value.ToString()))
        {
            MessageBox.Show("Item Already on List!");
            return;
        }
     }

     // lets add it!            
     int n = dataGridView3.Rows.Add();

     dataGridView3.Rows[n].Cells[1].Value = textBox43.Text;
     dataGridView3.Rows[n].Cells[4].Value = textBox4.Text;
     dataGridView3.Rows[n].Cells[2].Value = DateTime.Now.ToShortDateString();
     dataGridView3.Rows[n].Cells[3].Value = dateTimePicker3.Text;

     dataGridView3.FirstDisplayedScrollingRowIndex = n;
     dataGridView3.CurrentCell = dataGridView3.Rows[n].Cells[0];
     dataGridView3.Rows[n].Selected = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM