0

The code below is to retrieve a category for a particular id. it will only return just one value say "Sport" to the dataTable. How to i convert the dataTable value to a string. I want to make use of this value for other things in the application

var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString());
                    conn.Open();
                    var da = new SqlDataAdapter("Select Product_Category from Product 
            where 
                     Product_Id =" + fo, conn);
                     da.Fill(mydata);
                     conn.Close();
4
  • Use SqlCommand.ExecuteScalar Method () msdn.microsoft.com/en-us/library/… Commented May 9, 2017 at 11:07
  • ToString() might be of help Commented May 9, 2017 at 11:07
  • I can't tell if myData is a DataSet or DataTable. Here is solution : List<string> results = mydata.AsEnumerable().Select(x => x.Field<string>("Select Product_Category")).ToList(); or List<string> results = mydata.Table[0].AsEnumerable().Select(x => x.Field<string>("Select Product_Category")).ToList(); Commented May 9, 2017 at 11:16
  • if you have single column in datatable than you may check my answer. Commented Jun 20, 2019 at 8:08

2 Answers 2

1

you can use below code

string Product_Category = String.Empty;
if(mydata.Rows.Count>0)
{
Product_Category = mydata.Rows[0]["Product_Category"].ToString();
}

Assuming that mydata is DataTable here.

Sign up to request clarification or add additional context in comments.

1 Comment

made mistake with the code. mydata is a DataTable. I will check out your answer now
0

If you have a single column in datatable than it's simple to change datatable to string.

DataTable results = MyMethod.GetResults(); // i am getting data from getresult function
if(results != null && results.Rows.Count > 0)  // Check datatable is null or not
{
  List<string> lstring = new List<string>();
  foreach(DataRow dataRow in dt.Rows)
  {
     lstring.Add(Convert.ToString(dataRow["ColumnName"]));
  }
  string mainresult = string.Join(",", lstring.ToArray()); // You can Use comma(,) or anything which you want. who connect the two string. You may leave space also.
}
Console.WriteLine (mainresult);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.