2009-08-28 102 views
47

我有一個從SQL查詢填充到本地數據庫的DataTable,但我不知道如何從中提取數據。 主要方法(在​​測試程序):如何從DataTable中提取數據?

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

我用來創建我的數據庫中的表的命令:

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

我如何可以提取從DataTable數據轉換爲有意義的使用方式?

回答

115

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

馬克

+2

我知道這是一個古老的答案,但沒有你需要做一個投在foreach循環允許索引?我不能做這樣的事,直到我改變了代碼如下所示: 的foreach(DataRow的行YourDataTable.Rows.Cast ()) ... – awh112 2015-06-04 15:03:56

+0

即使較早的評論,但有沒有必要投射:'foreach'工作,因爲'行'是一個集合('DataRowCollection')。儘管如此,如果您想使用一些Linq方法(例如'.Where()'),您需要使用'.Cast ()'。 – 2016-11-29 17:27:18

+1

@marc_s謝謝 – 2017-01-06 13:19:00

16

您可以將數據表設置爲多個元素的數據源。

對於如

的GridView

中繼

DataList控件

等等等等

如果您需要從每一行提取數據,然後你可以使用

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

的foreach(在表的DataRow DR) table.Rows – StampedeXV 2009-08-28 10:30:00

3

除非你有特殊原因做原料ado.net我會看看使用ORM (對象關係映射器)像nhibernate或Linq到Sql。這樣,你可以查詢數據庫和retreive對象來處理強類型,並更容易與恕我直言。

科林摹

+1

在進入ORM之前,我得到了ADO.net的基本知識,正如http://stackoverflow.com/questions/1345508/how-do-i-connect-toa-a- SQL的數據庫,從-C/1345531#1345531 – RCIX 2009-08-28 10:51:06

4

請考慮使用像這樣的代碼:

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

請注意,打開和關閉使用DataAdapter的當連接是沒有必要的。

所以我建議請更新此代碼,刪除打開和關閉連接:

 SqlDataAdapter adapt = new SqlDataAdapter(cmd); 

conn.Open(); //這行代碼是uncessessary

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

conn.Close(); //這行代碼是uncessessary

 Console.WriteLine("connection closed successfuly"); 

Reference Documentation

在本例中所示的代碼沒有明確地打開和關閉連接 。 Fill方法隱式打開DataAdapter正在使用的Connection,如果它發現連接尚未打開,則爲 。如果Fill打開連接,則在填充完成時它也會關閉連接 。這可以簡化您的代碼,當您處理一個單一的操作,如填充或更新 。但是,如果你是 執行需要一個開放的連接多個操作,你 可以通過顯式調用 連接的Open方法,對 執行操作的數據源,然後調用Close方法提高應用程序的性能的連接。 您應儘可能保持數據源的連接,儘可能短暫地打開 以釋放資源以供其他客戶端應用程序使用。