C# 如何从DataTable中提取数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1346132/
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
How do I extract data from a DataTable?
提问by RCIX
I have a DataTable
that is filled in from an SQL query to a local database, but I don't know how to extract data from it.
Main method (in test program):
我有一个DataTable
从 SQL 查询填充到本地数据库的,但我不知道如何从中提取数据。主要方法(在测试程序中):
static void Main(string[] args)
{
const string connectionString = "server=localhost\SQLExpress;database=master;integrated Security=SSPI;";
DataTable table = new DataTable("allPrograms");
using (var conn = new SqlConnection(connectionString))
{
Console.WriteLine("connection created successfuly");
string command = "SELECT * FROM Programs";
using (var cmd = new SqlCommand(command, conn))
{
Console.WriteLine("command created successfuly");
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
conn.Open();
Console.WriteLine("connection opened successfuly");
adapt.Fill(table);
conn.Close();
Console.WriteLine("connection closed successfuly");
}
}
Console.Read();
}
The command I used to create the tables in my database:
我用来在我的数据库中创建表的命令:
create table programs
(
progid int primary key identity(1,1),
name nvarchar(255),
description nvarchar(500),
iconFile nvarchar(255),
installScript nvarchar(255)
)
How can I extract data from the DataTable
into a form meaningful to use?
如何将数据从 提取DataTable
到有意义的形式中使用?
采纳答案by marc_s
The DataTable has a collection .Rows
of DataRow elements.
DataTable 有一组.Rows
DataRow 元素。
Each DataRow corresponds to one row in your database, and contains a collection of columns.
每个 DataRow 对应于数据库中的一行,并包含一组列。
In order to access a single value, do something like this:
要访问单个值,请执行以下操作:
foreach(DataRow row in YourDataTable.Rows)
{
string name = row["name"].ToString();
string description = row["description"].ToString();
string icoFileName = row["iconFile"].ToString();
string installScript = row["installScript"].ToString();
}
Marc
马克
回答by rahul
You can set the datatable as a datasource to many elements.
您可以将数据表设置为许多元素的数据源。
For eg
例如
gridView
网格视图
repeater
中继器
datalist
数据列表
etc etc
等等等等
If you need to extract data from each row then you can use
如果您需要从每一行中提取数据,那么您可以使用
table.rows[rowindex][columnindex]
or
或者
if you know the column name
如果你知道列名
table.rows[rowindex][columnname]
If you need to iterate the table then you can either use a for loop or a foreach loop like
如果您需要迭代表,那么您可以使用 for 循环或 foreach 循环,例如
for ( int i = 0; i < table.rows.length; i ++ )
{
string name = table.rows[i]["columnname"].ToString();
}
foreach ( DataRow dr in table.Rows )
{
string name = dr["columnname"].ToString();
}
回答by pythonandchips
Unless you have a specific reason to do raw ado.net I would have a look at using an ORM (object relational mapper) like nhibernate or Linq to Sql. That way you can query the database and retreive objects to work with which are strongly typed and easier to work with IMHO.
除非你有特定的理由来做原始 ado.net,否则我会看看使用 ORM(对象关系映射器),如 nhibernate 或 Linq to Sql。通过这种方式,您可以查询数据库并检索要使用的对象,这些对象是强类型的并且更易于使用恕我直言。
Colin G
科林
回答by salimido
Please consider using some code like this:
请考虑使用一些这样的代码:
SqlDataReader reader = command.ExecuteReader();
int numRows = 0;
DataTable dt = new DataTable();
dt.Load(reader);
numRows = dt.Rows.Count;
string attended_type = "";
for (int index = 0; index < numRows; index++)
{
attended_type = dt.Rows[indice2]["columnname"].ToString();
}
reader.Close();
回答by Hamid Bahmanabady
var table = Tables[0]; //get first table from Dataset
foreach (DataRow row in table.Rows)
{
foreach (var item in row.ItemArray)
{
console.Write("Value:"+item);
}
}
回答by Rick
Please, note that Open and Close the connection is not necessary when using DataAdapter.
请注意,使用 DataAdapter 时不需要打开和关闭连接。
So I suggest please update this code and remove the open and close of the connection:
所以我建议请更新此代码并删除连接的打开和关闭:
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
conn.Open(); // this line of code is uncessessary
conn.Open(); // 这行代码是不必要的
Console.WriteLine("connection opened successfuly");
adapt.Fill(table);
conn.Close(); // this line of code is uncessessary
conn.Close(); // 这行代码是不必要的
Console.WriteLine("connection closed successfuly");
The code shown in this example does not explicitly open and close the Connection. The Fill method implicitly opens the Connection that the DataAdapter is using if it finds that the connection is not already open. If Fill opened the connection, it also closes the connection when Fill is finished. This can simplify your code when you deal with a single operation such as a Fill or an Update. However, if you are performing multiple operations that require an open connection, you can improve the performance of your application by explicitly calling the Open method of the Connection, performing the operations against the data source, and then calling the Close method of the Connection. You should try to keep connections to the data source open as briefly as possible to free resources for use by other client applications.
此示例中显示的代码未显式打开和关闭连接。如果发现连接尚未打开,Fill 方法会隐式打开 DataAdapter 正在使用的连接。如果 Fill 打开了连接,它也会在 Fill 完成时关闭连接。当您处理诸如填充或更新之类的单个操作时,这可以简化您的代码。但是,如果您正在执行需要打开连接的多个操作,则可以通过显式调用 Connection 的 Open 方法,对数据源执行操作,然后调用 Connection 的 Close 方法来提高应用程序的性能。您应该尝试尽可能短暂地保持与数据源的连接打开,以释放资源供其他客户端应用程序使用。
回答by haldo
The simplest way to extract data from a DataTable
when you have multiple data types (not just strings) is to use the Field<T>
extension method available in the System.Data.DataSetExtensions
assembly.
DataTable
当您有多种数据类型(不仅仅是字符串)时,从 a 中提取数据的最简单方法是使用Field<T>
程序集中可用的扩展方法System.Data.DataSetExtensions
。
var id = row.Field<int>("ID"); // extract and parse int
var name = row.Field<string>("Name"); // extract string
From MSDN, the Field<T>
method:
从MSDN,Field<T>
方法:
Provides strongly-typed access to each of the column values in the DataRow.
提供对 DataRow 中每个列值的强类型访问。
This means that when you specify the type it will validate and unbox the object.
这意味着当您指定类型时,它将验证并取消装箱对象。
For example:
例如:
// iterate over the rows of the datatable
foreach (var row in table.AsEnumerable()) // AsEnumerable() returns IEnumerable<DataRow>
{
var id = row.Field<int>("ID"); // int
var name = row.Field<string>("Name"); // string
var orderValue = row.Field<decimal>("OrderValue"); // decimal
var interestRate = row.Field<double>("InterestRate"); // double
var isActive = row.Field<bool>("Active"); // bool
var orderDate = row.Field<DateTime>("OrderDate"); // DateTime
}
It also supports nullable types:
它还支持可为空类型:
DateTime? date = row.Field<DateTime?>("DateColumn");
This can simplify extracting data from DataTable
as it removes the need to explicitly convert or parse the object into the correct types.
这可以简化从中提取数据的过程,DataTable
因为它消除了将对象显式转换或解析为正确类型的需要。