• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1971
  • Last Modified:

How do i get a particular cell from a datatable

I have a datatable and i want to grab the value of a cell and display it else where but i'm not sure how to go about it - could someone please help point it out...tha
0
mrperfect75000
Asked:
mrperfect75000
  • 3
  • 2
1 Solution
 
JimBrandleyCommented:
You can get the value as:
string content = yourDataTable.Rows[rowIndex][columnIndex].ToString();

Jim
0
 
mrperfect75000Author Commented:
what type is the rowindex? sorry for not understanding this... but i'm not sure how to get the rowindex and column index
0
 
JimBrandleyCommented:
They are just integers. Sy you want the value from the third row, 4th column, then:
string content = yourDataTable.Rows[2][3].ToString();

Jim
0
 
mrperfect75000Author Commented:
Thanks for your help.

This works, however, i wanted to get it programatically because i'm making a method that will be called several times.

I have about 5 columns and many rows

Here is what i'm trying to do...

public static DataTable makeadatable(int ID)

{

DataTable newdt = new DataTable();
        using (SqlConnection cnn = new SqlConnection(blahblah)
        {
            cnn.Open();
            using (SqlCommand cmd = new SqlCommand("mysp", cnn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("@ID", id));
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                sda.Fill(newdt);
            }
        }

        return newdt;


}

Then i'm calling it like this....


id = textbox1.text
string name =  myclass.makeadatable(id).Rows[].[].ToString();


what do i put in them programatically to get the appropriate name based on the ID?

Thanks for your help!
0
 
JimBrandleyCommented:
You need to change one bit:
DataTable myData =  myclass.makeadatable(id);

Now, what happens next depends on what you want to do with the content of the DataTable. If you want to iterate over the rows, and get the value from each of the five columns, you could do something like this:
string col1Value = string.Empty;
string col2Value = string.Empty;
string col3Value = string.Empty;
string col4Value = string.Empty;
string col5Value = string.Empty;

foreach (DataRow row in myData)
{
   col1Value = row[0].ToString();
   col2Value = row[1].ToString();
   col3Value = row[2].ToString();
   col4Value = row[3].ToString();
   col5Value = row[4].ToString();
   // Now, you need to do something with the strings before the content is overwritten by the next row.
}

Jim
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now