Reputation: 59
I use this code for getting data from SQL Server:
string rootname = "[" + nameroot + "]";
string retVal = "";
string constring = "Data Source =(Local);Initial Catalog=Tajari;Integrated Security=True;";
SqlConnection conobj = new SqlConnection(constring);
string commandtext = "select distinct " + rootname + " from TBLJobsRootName where MenuId between 1 and " + countroot + "";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
//retVal = dr[nameroot].ToString();
}
conobj.Close();
Now I need this data inserted into a variable or textbox.
The problem is that my values are unknown
Upvotes: 1
Views: 1875
Reputation: 26209
Solution 1 :
You can use Index
value.
Try This:
while (dr.Read())
{
retVal = dr[0].ToString();
}
Solution 2 :
You can also use alias name.
string commandtext = "select distinct " + rootname + " as myrootname from
TBLJobsRootName where MenuId between 1 and " + countroot + "";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
retVal = dr["myrootname"].ToString();
}
Suggestion: Your Query is open to SQL Injection Attacks i would suggest you to use Parameterised Queries to avoid them.
Solution 3: Using Parameterised Queries
if you want to add all rootname values you need to add all values to List.
List<string> list = new List<string>();
string commandtext = "select distinct "+rootname+" as myrootname from
TBLJobsRootName where MenuId between 1 and @countroot";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
comobj.Parameters.AddWithValue("@countroot",countroot);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
lis.Add(dr["myrootname"].ToString());
}
//You can retunrn list
Upvotes: 3