开发者

Getting value from a DataSet into a variable

开发者 https://www.devze.com 2023-04-02 05:22 出处:网络
I have the following method which returns dataset. I am using .NET 2.0 DataSet ds = GetAllRecords(); I want to get values from each column for a particular row and bind it to a variable.

I have the following method which returns dataset. I am using .NET 2.0

DataSet ds = GetAllRecords();

I want to get values from each column for a particular row and bind it to a variable. How can this be achieved?

currently the method returns all the row from the table and I have to find that particular row based on ID.

However, if that is not possible I can come with

DataSet ds = GetSpecificRecord(i开发者_运维问答d);

But I still need to get values from each column and bind it to variable. Please advice.


// Create a table 
DataTable table = new DataTable("users");
table.Columns.Add(new DataColumn("Id", typeof(int)));
table.Columns.Add(new DataColumn("Name", typeof(string)));

table.Rows.Add(1, "abc");
table.Rows.Add(2, "ddd");
table.Rows.Add(3, "fff");
table.Rows.Add(4, "hhh d");
table.Rows.Add(5, "hkf ds");

// Search for given id e.g here 1

DataRow[] result = table.Select("Id = 1"); // this will return one row for above data 
foreach (DataRow row in result)
{
    Console.WriteLine("{0}, {1}", row[0], row[1]);
}


This will get you the value from Row 0 obviously you would need to modify for multiple rows returned

long id = ds.Tables[0].Rows[0].Field<long>("ID");


You can do this with LINQ.

DataRow resultRow = ds.Tables["SomeTable"].AsEnumerable().Where(row => row.Field<int>("SomeID") == 1).FirstOrDefault();

For .NET 2.0 and below

If your DataTable has a primary key defined, you can find the row like this:

DataTable table = ds.Tables["SomeTable"];
DataRow row = table.Rows.Find(1);

If there is no primary key, you can assign one like this:

DataTable table = ds.Tables["SomeTable"];
table.PrimaryKey = new DataColumn[] { table.Columns["SomeID"] };

DataRow row = table.Rows.Find(1);

Another option is to use the RowFilter property of the DefaultView, like this:

DataTable table = ds.Tables["SomeTable"];

table.DefaultView.RowFilter = "SomeID == 1"; //not sure if it's == or = here
DataRow row = table.DefaultView[0].Row;

Lastly, you can also use the DataTable.Select() method to find rows.


Have you looked at using a typed dataset? If you're looking for a row based on the primary key of a table it will autogenerate a method for you to get a row by ID and it will be strongly typed so you can get column values by name.

They were quite handy in .Net 2.0 - but LINQ made them fairly obsolete.

Edit: A slightly better reference URL

http://www.c-sharpcorner.com/UploadFile/rupadhyaya/TypedDataSets12032005021013AM/TypedDataSets.aspx


We can get value from dataset by using this easy method:

  System.Data.DataSet ds = db.MySelect(
                    "Fields",
                    "Table",
                     "Condition"
                     );

        if (ds != null)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
               object value=Tables[0].Rows[indx]["field name"];
            }
        }


To fetch values from student table and display it in console window.

class Class1
{
    static void Main(string[] args)
    { 
          SqlConnection con=new SqlConnection(<connectionstring>);           
          SqlCommand cmd = new SqlCommand("select * from Student", con);
          SqlDataAdapter ad = new SqlDataAdapter(cmd);
          DataSet ds=new DataSet();
          ad.Fill(ds);
          for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
          {
              try
              {

                  DataRow r = ds.Tables[0].Rows[i];
                  Console.WriteLine(r.Field<Int32>(0));
                  Console.WriteLine(r.Field<String>(1));
                  Console.WriteLine(r.Field<String>(2));
                  Console.WriteLine(r.Field<Decimal>(3));
                  Console.WriteLine(r.Field<Int16>(4));

              }
              catch (Exception ex)
              {
                  Console.WriteLine(ex);
              }
          }

          Console.ReadKey();
    }
}

sql Student table Info

Id int
Name varchar(50)
EmailId nvarchar(50)
MobileNo numeric(10,0)
Standard smallint
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号