如何从一个DataTable中提取数据? [英] How do i extract data from a DataTable?

查看:809
本文介绍了如何从一个DataTable中提取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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):

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?

推荐答案

该数据表具有收藏 .Rows DataRow的元素。

The DataTable has a collection .Rows of DataRow elements.

每个的DataRow对应一个排在数据库中,并且包含列的集合

Each DataRow corresponds to one row in your database, and contains a collection of columns.

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

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

 }

马克·

这篇关于如何从一个DataTable中提取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆