如何从DataTable中提取数据?

我有一个从SQL查询填充到本地数据库的DataTable ,但我不知道如何从中提取数据。 主要方法(在​​testing程序中):

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

我用来在我的数据库中创build表的命令:

 create table programs ( progid int primary key identity(1,1), name nvarchar(255), description nvarchar(500), iconFile nvarchar(255), installScript nvarchar(255) ) 

我怎样才能从DataTable提取数据到一个有意义的forms使用?

DataTable具有DataRow元素的集合.Rows

每个DataRow对应于数据库中的一行,并包含一组列。

为了访问一个单一的值,做这样的事情:

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

渣子

您可以将数据表设置为多个元素的数据源。

例如

网格视图

中继器

数据列表

等等

如果你需要从每一行提取数据,那么你可以使用

 table.rows[rowindex][columnindex] 

要么

如果你知道列名

 table.rows[rowindex][columnname] 

如果你需要迭代表,那么你可以使用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(); } 

请考虑使用这样的代码:

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

除非你有一个特定的原因做原始ado.net我会看看使用ORM(对象关系映射器)像nhibernate或Linq到SQL。 这样,你可以查询数据库和retreive对象与强大的types,更容易与恕我直言的工作。

科林G

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

请注意,在使用DataAdapter时,打开和closures连接是不必要的。

所以我build议请更新这段代码,并删除连接的打开和closures:

  SqlDataAdapter adapt = new SqlDataAdapter(cmd); 

conn.Open(); //这行代码是不必要的

  Console.WriteLine("connection opened successfuly"); adapt.Fill(table); 

conn.Close(); //这行代码是不必要的

  Console.WriteLine("connection closed successfuly"); 

参考文档

此示例中显示的代码不显式打开和closures连接。 Fill方法隐式打开DataAdapter正在使用的Connection,如果它发现连接尚未打开。 如果填充打开连接,则填充完成后也会closures连接。 当您处理单个操作(如填充或更新)时,这可以简化您的代码。 但是,如果要执行需要打开连接的多个操作,则可以通过显式调用Connection的Open方法,对数据源执行操作,然后调用Connection的Close方法来提高应用程序的性能。 您应尽可能保持与数据源连接的连接,以释放资源供其他客户端应用程序使用。