C# 将值添加到特定的 DataTable 单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12292287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:46:17  来源:igfitidea点击:

Adding values to specific DataTable cells

c#datagridviewdatagriddatatable

提问by Winz

I'm wondering if it's possible to add values to specific DataTable cells?

我想知道是否可以向特定的 DataTable 单元格添加值?

Suppose I have an existing dataTable and I add a new column, how would I go about adding to the new column's rows without overwriting the existing columns' rows?

假设我有一个现有的 dataTable 并且我添加了一个新列,我将如何在不覆盖现有列的行的情况下添加到新列的行?

As far as I'm aware, there isn't a method for adding to specific cells (unless I'm wrong).

据我所知,没有添加到特定单元格的方法(除非我错了)。

  dt.Rows.Add(a, b, c, d)

where a, b, c and d are string values. So what if I just want to add to the d column?

其中 a、b、c 和 d 是字符串值。那么如果我只想添加到 d 列呢?

Any help would be appreciated.

任何帮助,将不胜感激。

采纳答案by pinkfloydx33

If it were a completely new row that you wanted to only set one value, you would need to add the whole row and then set the individual value:

如果它是一个全新的行,您只想设置一个值,则需要添加整行,然后设置单个值:

DataRow dr = dt.NewRow();
dr[3].Value = "Some Value";
dt.Rows.Add(dr);

Otherwise, you can find the existing row and set the cell value

否则,您可以找到现有行并设置单元格值

DataRow dr = dt.Rows[theRowNumber];
dr[3] = "New Value";

回答by lc.

You mean you want to add a new row and only put data in a certain column? Try the following:

你的意思是你想添加一个新行并且只将数据放在某个列中?请尝试以下操作:

var row = dataTable.NewRow();
row[myColumn].Value = "my new value";
dataTable.Add(row);

As it is a data table, though, there will always be data of some kind in every column. It just might be DBNull.Valueinstead of whatever data type you imagine it would be.

但是,由于它是数据,因此每列中总会有某种数据。它可能DBNull.Value不是您想象的任何数据类型。

回答by Pedigree

I think you can't do that but atleast you can update it. In order to edit an existing row in a DataTable, you need to locate the DataRow you want to edit, and then assign the updated values to the desired columns.

我认为你不能这样做,但至少你可以更新它。为了编辑 DataTable 中的现有行,您需要找到要编辑的 DataRow,然后将更新的值分配给所需的列。

Example,

例子,

DataSet1.Tables(0).Rows(4).Item(0) = "Updated Company Name"
DataSet1.Tables(0).Rows(4).Item(1) = "Seattle"

SOURCE HERE

来源在这里

回答by Teekai

Try this:

尝试这个:

dt.Rows[RowNumber]["ColumnName"] = "Your value"

For example: if you want to add value 5 (number 5) to 1st row and column name "index" you would do this

例如:如果您想将值 5(数字 5)添加到第一行和列名称“索引”,您可以这样做

dt.Rows[0]["index"] = 5;

I believe DataTable row starts with 0

我相信 DataTable 行以 0 开头

回答by MX313

If anyone is looking for an updated correct syntax for this as I was, try the following:

如果有人像我一样为此寻找更新的正确语法,请尝试以下操作:

Example:
dg.Rows[0].Cells[6].Value = "test";