I have several Label controls in my page and a stored procedure that always return 1 row. I want to call the same stored procedure with different parameter. Can anybody who me how to do this?
I have a function that contains:
DataSet objDs =new DataSet();
System.Data.SqlClient.SqlConnection myConnection =new System.Data.SqlClient.SqlConnection(
System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);System.Data.SqlClient.SqlDataAdapter cmd;
cmd =new System.Data.SqlClient.SqlDataAdapter("sp_getCounter1", myConnection);cmd.SelectCommand.CommandType = CommandType.StoredProcedure;
cmd.SelectCommand.Parameters.Add(
new SqlParameter("@dotnet.itags.org.param1", mode));
DataTable dtMasterListe =new DataTable("mytable");myConnection.Open();
cmd.Fill(objDs);
With the above code it is easy to e.g bind to datagrid, but I want to achiveve the following Label1.Text = objDs.getstring(etc).
Any clues?
public string FunctionName(){using (SqlConnection cn =new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString)) { SqlCommand cmd =new SqlCommand("StoredProcedureName", cn); cmd.CommandType = CommandType.StoredProcedure;// Add parameters if needed cn.Open();return (string)ExecuteScalar(cmd); }}void Page_Load(){ Label1.Text = FunctionName()}
This is what I usually do:
If you already sure the dataset only contains 1 table and 1 row only, then you can use the following to get the data you want:
Label1.Text = ds.Tables[0].Rows[0][0].ToString();
If you know the table name returned in the dataset, you can also pass in the tablename:
Label1.Text = ds.Tables["tablename"].Rows[0][0].ToString();
It will even be better if you can specify the column name:
Label1.Text = ds.Tables["tablename"].Rows[0]["Name"].ToString();
I usually check if the number of tables & rows > 0 then only get the value:
if ((ds.Tables.Count == 0) && (ds.Tables["tablename"].Rows.Count == 0))
Hope this helps. ^_^
Hi,
If you know that your stored procedure will return only one row all the time, then go for theExcecuteScalar method.
Works perfect!
Had to make a minor change:
int ret = (int)cmd.ExecuteScalar();
return ret.ToString();
to make ExecuteScalar to work.
Thanks.
0 comments:
Post a Comment