如何从C#中的数据表中获取datarow值 [英] How to get the datarow value from datatable in C#

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

问题描述

你好



我有一个包含一些记录的数据表。数据表列是(ID,NAME,CONTACT)

现在我想通过提供ID找到名称和联系人。





假设选择NAME,CONTACT,其中ID = 1.



我尝试过:



这里我找到了该数据表的数据行。如下所示



hello

i have a datatable which contain some record. the datatable column are (ID,NAME,CONTACT)
Now i wanted to find the Name and Contact by providing the ID.


suppose select NAME , CONTACT where ID = 1.

What I have tried:

here i have finded the data row of that datatable. like below

DataRow[] dr = dt.Select("ID= 1");





但如何从Datarow获取NAME和CONTACT号码[]



but how to get the NAME and CONTACT number from Datarow[]

推荐答案

DataRow[] dr = dt.Select("ID= 1");

foreach(DataRow row in dr)
{
    var name = row["NAME"].ToString();
    var contact = row["CONTACT"].ToString();
}

使用System.Data中的'字段扩展方法,我们可以简化从'对象到其本机类型:

Using the 'Field extension method in System.Data, we can make simpler the casting of Column values from 'object to their native Type:

DataRow[] dr = dt.Select("ID= 1");

foreach(DataRow row in dr)
{
    string name = row.Field<string>("NAME");
    string contact = row.Field<string>("CONTACT");
}

您真的需要查看使用DataTable的基础知识:[ ^ ],[ ^ ]。

You really need to review the "basics" of using a DataTable: [^], [^].


考虑到ID是唯一的,你总会得到一行,所以,你真的不需要循环:),只需使用索引为0的datarow数组来获取NAME和CONTACT,如下所示。



Considering ID is unique you will always get a single row, so, you do not really need to loop :), just use datarow array with index as 0 to get the NAME and CONTACT like below.

DataRow[] dr = dt.Select("ID= 1");
var name = dr[0]["NAME"].ToString();
var contact = dr[0]["CONTACT"].ToString();


这篇关于如何从C#中的数据表中获取datarow值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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