I am getting unable to store datatable value in string . How to return a string value of a data table? It gives an error while returning scalar value.
An exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll but was not handled in user code-- error in return statement
txtSalespersonName.Text = dl.GetStringValue("select top 1 [ContactPerson] from tbl_Companies where Company='" +companyname + "' order by id desc");
public string GetStringValue(string query)
{
DataTable dt = new DataTable();
try
{
string constr = ConfigurationManager.ConnectionStrings["KernelCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
}
}
catch (Exception ex)
{
// Response.Write(ex.Message);
}
return dt.Rows[1].ToString();
}
dt.Rows[0]because it is the first element ?dt.Rows[0][0].ToString()ordt.Rows[0]["Name"].ToString()