How to programmatically set cell value in DataGridView?

前端 未结 14 840
無奈伤痛
無奈伤痛 2020-11-30 02:05

I have a DataGridView. Some of the cells receive their data from a serial port: I want to shove the data into the cell, and have it update the underlying bound object.

相关标签:
14条回答
  • 2020-11-30 02:47

    Just like @Thomas said, the element you want to change must implement INotifyPropertyChanged. But, datasource is also important. It has to be BindingList, which you can create easily from List.

    Here is my example - data source is at first DataTable, which I transfer to List and then create BindingList. Then I create BindingSource and use BindingList as DataSource from BindingSource. At last, DataSource from DataGridView uses this BindingSource.

     sp_Select_PersonTableAdapter adapter = new sp_Select_PersonTableAdapter();
    
     DataTable tbl = new DataTable();
     tbl.Merge(adapter.GetData());
    
     List<Person> list = tbl.AsEnumerable().Select(x => new Person
     {
         Id = (Int32) (x["Id"]),
         Ime = (string) (x["Name"] ?? ""),
         Priimek = (string) (x["LastName"] ?? "")
     }).ToList();
    
     BindingList<Person> bindingList = new BindingList<Person>(list);
    
     BindingSource bindingSource = new BindingSource();
     bindingSource.DataSource = bindingList;
     dgvPerson.DataSource = bindingSource;
    

    What is also very important: each class's member setter must call OnPropertyChanged(). Without that, it won't work. So, my class looks like this:

    public class Person : INotifyPropertyChanged
        {
            private int _id;
            private string _name;
            private string _lastName;
    
            public int Id
            {
                get { return _id; }
                set
                {
                    if (value != _id)
                    {
                        _id = value;
                        OnPropertyChanged();
                    }
                }
            }
            public string Name
            {
                get { return _name; }
                set
                {
                    if (value != _name)
                    {
                        _name = value;
                        OnPropertyChanged();
                    }
                }
            }
            public string LastName
            {
                get { return _lastName; }
                set
                {
                    if (value != _lastName)
                    {
                        _lastName= value;
                        OnPropertyChanged();
                    }
                }
            }
            public event PropertyChangedEventHandler PropertyChanged;
    
            [NotifyPropertyChangedInvocator]
            protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                PropertyChangedEventHandler handler = PropertyChanged;
                if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
            }
    
        }
    

    More on this topic: http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx

    0 讨论(0)
  • 2020-11-30 02:50

    I searched for the solution how I can insert a new row and How to set the individual values of the cells inside it like Excel. I solved with following code:

    dataGridView1.ReadOnly = false; //Before modifying, it is required.
    dataGridView1.Rows.Add(); //Inserting first row if yet there is no row, first row number is '0'
    dataGridView1.Rows[0].Cells[0].Value = "Razib, this is 0,0!"; //Setting the leftmost and topmost cell's value (Not the column header row!)
    dataGridView1[1, 0].Value = "This is 0,1!"; //Setting the Second cell of the first row!
    

    Note:

    1. Previously I have designed the columns in design mode.
    2. I have set the row header visibility to false from property of the datagridview.
    3. The last line is important to understand: When yoou directly giving index of datagridview, the first number is cell number, second one is row number! Remember it!

    Hope this might help you.

    0 讨论(0)
  • 2020-11-30 02:51

    I had the same problem with sql-dataadapter to update data and so on

    the following is working for me fine

    mydatgridview.Rows[x].Cells[x].Value="test"
    mydatagridview.enabled = false 
    mydatagridview.enabled = true 
    
    0 讨论(0)
  • 2020-11-30 02:53

    Do you remember to refresh the dataGridView?

    datagridview.refresh();
    
    0 讨论(0)
  • 2020-11-30 02:54
    private void btn_Addtoreciept_Click(object sender, EventArgs e)
    {            
        serial_number++;
        dataGridView_inventory.Rows[serial_number - 1].Cells[0].Value = serial_number;
        dataGridView_inventory.Rows[serial_number - 1].Cells[1].Value =comboBox_Reciept_name.Text;
        dataGridView_inventory.Rows[serial_number - 1].Cells[2].Value = numericUpDown_recieptprice.Value;
        dataGridView_inventory.Rows[serial_number - 1].Cells[3].Value = numericUpDown_Recieptpieces.Value;
        dataGridView_inventory.Rows[serial_number - 1].Cells[4].Value = numericUpDown_recieptprice.Value * numericUpDown_Recieptpieces.Value;
        numericUpDown_RecieptTotal.Value = serial_number;
    }
    

    on first time it goes well but pressing 2nd time it gives me error "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index" but when i click on the cell another row appears and then it works for the next row, and carry on ...

    0 讨论(0)
  • 2020-11-30 02:55

    I tried a lot of methods, and the only one which worked was UpdateCellValue:

    dataGridView.Rows[rowIndex].Cells[columnIndex].Value = "New Value";
    dataGridView.UpdateCellValue(columnIndex, rowIndex);
    

    I hope to have helped. =)

    0 讨论(0)
提交回复
热议问题