首页 文章

如何在DataGridView中以编程方式设置单元格值?

提问于
浏览
35

我有一个DataGridView . 一些单元从串口接收数据:我想将数据推入单元,并让它更新底层绑定对象 .

我正在尝试这样的事情:

SetValueFromSerial (decimal newValue)
{
    dataGridView.CurrentCell.Value = newValue;
}

使用字符串没有帮助:

dataGridView.CurrentCell.Value = newValue.ToString ();

在这两种情况下,我都没有在网格中看到任何内容,并且基础值没有变化 .

我在谷歌搜索并在这里搜索,但我并没有完全懒惰 . )

14 回答

  • 28

    试试这种方式:

    dataGridView.CurrentCell.Value = newValue;
    
    dataGridView.EndEdit();
    
    dataGridView.CurrentCell.Value = newValue;
    
    dataGridView.EndEdit();
    

    需要写两次......

  • 4

    以下作品 . 我可能会弄错,但添加一个 String 值并没有尝试或尝试任何黑客攻击) .

    DataGridViewName.Rows[0].Cells[0].Value = 1;
    
  • 5

    如果 DataGridView 是数据绑定,则不应直接修改单元格的内容 . 相反,您应该修改数据绑定对象 . 您可以通过 DataGridViewRowDataBoundItem 访问该对象:

    MyObject obj = (MyObject)dataGridView.CurrentRow.DataBoundItem;
    obj.MyProperty = newValue;
    

    请注意,绑定对象应实现 INotifyPropertyChanged ,以便更改反映在 DataGridView

  • 3
    dataGridView1[1,1].Value="tes";
    
  • 4

    如果您不想出于某种原因修改数据绑定对象(例如,您希望在网格中显示某些视图,但不希望它作为数据源对象的一部分),您可能希望这样做:

    1.手动添加列:

    DataGridViewColumn c = new DataGridViewColumn();
        DataGridViewCell cell = new DataGridViewTextBoxCell();
    
        c.CellTemplate = cell;
        c.HeaderText = "added";
        c.Name = "added";
        c.Visible = true;
    dgv.Columns.Insert(0, c);
    

    2.在DataBindingComplete事件中执行以下操作:

    foreach (DataGridViewRow row in dgv.Rows)
    {if (row.Cells[7].Value.ToString()=="1")
    row.Cells[0].Value = "number one"; }
    

    (只是一个愚蠢的例子)

    但请记住,IT必须在DataBindingComplete中,否则值将保持空白

  • 1

    你还记得refresh dataGridView吗?

    datagridview.refresh();
    
  • 4

    我有与sql-dataadapter相同的问题来更新数据等等

    以下对我很好

    mydatgridview.Rows[x].Cells[x].Value="test"
    mydatagridview.enabled = false 
    mydatagridview.enabled = true
    
  • 0

    我搜索了如何插入新行的解决方案以及如何像Excel一样设置其中单元格的各个值 . 我解决了以下代码:

    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!
    

    注意:

    • 以前我在设计模式下设计了列 .

    • 我已经从datagridview的属性将行 Headers 可见性设置为false .

    • 最后一行很重要:当你直接给出datagridview的索引时,第一个数字是单元格号,第二个是行号!记住它!

    希望这可能对你有所帮助 .

  • 1

    如果 DataGridView 已填充 DataGridView (即数据绑定),则需要更改绑定数据,而不是DataGridView单元本身 .

    因此,从已知行或列获取该数据的一种方法是:

    (YourRow.DataBoundItem as DataRowView).Row['YourColumn'] = NewValue;
    
  • 0

    我遇到了同样的问题并解决了如下的VB.NET . 它是.NET Framework,因此您应该可以适应 . 想要比较我的解决方案,现在我发现没有人似乎按我的方式解决它 .

    进行现场声明 .

    Private _currentDataView as DataView

    因此,循环遍历所有行并搜索包含我知道的值的单元格,我想要更改的单元格旁边适用于我 .

    Public Sub SetCellValue(ByVal value As String)
        Dim dataView As DataView = _currentDataView
    
        For i As Integer = 0 To dataView.Count - 1
            If dataView(i).Row.Item("projID").ToString.Equals("139") Then
                dataView(i).Row.Item("Comment") = value
                Exit For ' Exit early to save performance
            End If
        Next
    End Sub
    

    这样你就可以更好地理解它 . 我知道ColumnName“projID”是139.我循环直到找到它然后我可以在我的案例“Comment”中更改“ColumnNameofCell”的值 . 我将此用于运行时添加的注释 .

    dataview

  • 1

    在VB中你可以使用这个

    Dim selectedRow As DataRowView
    selectedRow = dg.Rows(dg.CurrentCell.RowIndex).DataBoundItem
    selectedRow("MyProp") = "myValue"
    dg.NotifyCurrentCellDirty(True)
    

    感谢saeed serpooshan的最后一排

  • 1

    就像@Thomas所说,要更改的元素必须实现INotifyPropertyChanged . 但是,数据源也很重要 . 它必须是BindingList,您可以从List轻松创建 .

    这是我的例子 - 数据源首先是DataTable,我将其传输到List然后创建BindingList . 然后我创建BindingSource并使用BindingList作为BindingSource的DataSource . 最后,DataGridView的DataSource使用这个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;
    

    同样重要的是:每个类的成员setter必须调用OnPropertyChanged() . 没有它,它将无法工作 . 所以,我的 class 看起来像这样:

    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));
            }
    
        }
    

    有关此主题的更多信息:http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx

  • 0
    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;
    }
    

    在第一次它进展顺利,但按第二次它给我错误“索引超出范围 . 必须是非负的,小于集合的大小 . 参数名称:索引”但当我点击单元格时出现另一行然后它适用于下一行,并继续......

  • 33

    我尝试了很多方法,唯一有效的方法是UpdateCellValue:

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

    我希望能有所帮助 . =)

相关问题