Reputation: 30313
how to assign database value to arrays. i tried like this...
da = new SqlDataAdapter("select emname from emp", con);
ds = new DataSet();
da.Fill(ds, "emp");
if(ds.Tables [0].Rows.Count >0)
{
for(int i=0;i<ds.Tables [0].Rows .Count ;i++)
{
string[] myArray = ds.Tables[0].Rows[i]["emname"].ToString();
}
}
but it is giving error that can't convert string to string[] please help me
Upvotes: 1
Views: 2005
Reputation: 3405
If you want an array of all the names, you can just convert an array of DataRow
into an array of string
like that:
da = new SqlDataAdapter("select emname from emp", con);
ds = new DataSet();
da.Fill(ds, "emp");
string[] myArray = Array.ConvertAll<DataRow, string>(ds.Tables[0].Select(),
delegate(DataRow row) { return row["emname"].ToString(); });
Upvotes: 0
Reputation: 2391
You are trying to innitialize a new array on every loop, and on top of that you are also trying to assign it as a string and not an array.
string[][] myArray = ds.Tables[0].Rows would be the proper solution. Also note that rows is a multidimentional array. You could also use for example string[] myArray = dt.Tables[0].Rows[0] if you want an array populated with a specific row.
Upvotes: 0
Reputation: 1500805
Try this:
da = new SqlDataAdapter("select emname from emp", con);
ds = new DataSet();
da.Fill(ds, "emp");
if(ds.Tables[0].Rows.Count > 0)
{
string[] myArray = new string[ds.Tables[0].Rows.Count];
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
myArray[i] = ds.Tables[0].Rows[i]["emname"].ToString();
}
// Use myArray here...
}
Note that there are neater ways of doing this using LINQ, but if you're quite new to C#/.NET I'd advise you to become familiar with the basics before diving into LINQ.
Upvotes: 5