How to display data on label using stored procedure - asp.net

I am trying to display data using stored procedure on a label but I am not getting any output.
using(SqlConnection con=new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("service_profile", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlParameter sp_id1 = new SqlParameter("#sp_id",sp_id);
SqlParameter rbx = new SqlParameter("#ReturnCode",rb);
cmd.Parameters.Add(sp_id1);
cmd.Parameters.Add(rbx);
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Label2.Text = Convert.ToString(reader["sp_name"]);
}
}

Related

The variable name #IdLiquidacion has already been declared. Variable names must be unique within a query batch or stored procedure.'

I have the following problem when inserting the info in the databases
public void Insertar()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=BD-DLLO-SP2016;Initial Catalog=GobernacionCesar;Integrated Security=True";
con.Open();
string query = "INSERT INTO Liquidacion (IdLiquidacion, IdPeriodo, FechaGeneracion, Usuario) VALUES(#IdLiquidacion, #IdPeriodo, #FechaGeneracion, #Usuario)";
SqlCommand com1 = new SqlCommand(query, con);
foreach (GridViewRow gridRow in GridView4.Rows)
{
Iniciar();
com1.Parameters.AddWithValue("#IdLiquidacion", A);
com1.Parameters.AddWithValue("#IdPeriodo", cell);
com1.Parameters.AddWithValue("#FechaGeneracion", DateTime.Now.ToString());
com1.Parameters.AddWithValue("#Usuario", gridRow.Cells[0].Text);
com1.ExecuteNonQuery();
}
con.Close();
return;
}
Move the command
SqlCommand com1 = new SqlCommand(query, con);
to the beginning of the loop:
foreach (GridViewRow gridRow in GridView4.Rows)
{
SqlCommand com1 = new SqlCommand(query, con);
....
}
You should
define the parameters outside of the loop
only set the values for the parameters inside the loop
Like this:
SqlCommand com1 = new SqlCommand(query, con);
// define parameters - you need to adapt the datatypes - I was only guessing
com1.Parameters.Add("#IdLiquidacion", SqlDbType.Int);
com1.Parameters.Add("#IdPeriodo", SqlDbType.VarChar, 50);
com1.Parameters.Add("#FechaGeneracion", SqlDbType.DateTime);
com1.Parameters.Add("#Usuario", SqlDbType.VarChar, 100);
foreach (GridViewRow gridRow in GridView4.Rows)
{
Iniciar();
// inside the loop, only SET the values
com1.Parameters["#IdLiquidacion"].Value = A;
com1.Parameters["#IdPeriodo"].Value = cell;
com1.Parameters["#FechaGeneracion"].Value = DateTime.Now;
com1.Parameters["#Usuario"].Value = gridRow.Cells[0].Text;
com1.ExecuteNonQuery();
}
You're adding the parameters in the loop. If you clear them before adding, this should work.

Unable to select item name in DropDownList on selectedindex_changed event?

Code in Page_Load() event is as follows :-
SqlConnection c = new SqlConnection(conn);
c.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = c;
cmd.CommandText = "select name from Employee1";
SqlDataReader dr = cmd.ExecuteReader();
if (!IsPostBack)
{
while (dr.Read())
{
DropDownList1.Items.Add(dr["name"].ToString());
}
}
Code in DropDownList1_SelectedIndexChanged() event is as follows:-
Label1.Text = DropDownList1.SelectedItem.ToString();
I also tried writing
Label1.Text = DropDownList1.SelectedItem.Text;
Label1.Text = DropDownList1.SelectedItem;
I wan't to use that name in following query
cmd.CommandText = "select salary from Employee1 where name='"
+DropDownList1.SelectedItem.Text+"' ";
Use if !Page.IsPostback to bind the data.
if (!Page.IsPostBack)
{
//bind your dropdown here
SqlConnection c = new SqlConnection(conn);
c.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = c;
cmd.CommandText = "select name from Employee1";
SqlDataReader dr = cmd.ExecuteReader();
if (!IsPostBack)
{
while (dr.Read())
{
DropDownList1.Items.Add(dr["name"].ToString());
}
}
}
bind your DropDownList as below
if (!Page.IsPostBack)
{
DataTable dt= new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("select name, salary from Employee1", conn);
adapter.Fill(dt);
DropDownList1.DataSource = dt
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "salary";
DropDownList1.DataBind();
}
then DropDownList1.SelectedValue give you the salary of selected item, no need to initiate another database call.

Data list results not disalying in my page

I tried the code below for displaying results in data list. When user logs in, I tried to pull the data according to their id, but the details do not display, here is my code:
string connn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection con = new SqlConnection(connn);
con.Open();
string str = "select details,address
from tb_userdata
inner join tb_userlogin
on tb_userdata.uidfromtb1=tb_userlogin.id";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
Can any one tell me what is the problem with this code?
Your SQL query is missing WHERE statement. What you have in your query should show details for all users and not only for that specific user.
Try something like this and just update the part where parameter value is added
string connn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection con = new SqlConnection(connn);
con.Open();
string str = "select details,address from tb_userdata inner join tb_userlogin on tb_userdata.uid=tb_userlogin.id WHERE tb_userlogin.uid = #UID";
SqlCommand cmd = new SqlCommand(str, con);
cmd.Parameters.Add(new SqlParameter("#UID", "retrieve UID somehow");
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
con.Dispose();

Can i bind same datareader object to 2 controls?

I am trying to bind same data reader object to 2 controls .one is gridview and second is formview.The gridview is getting bind but it formview didn't .Even i am closing the object after binding both.
Can anyone please let me know if it is possible or not.If yes then how?
This is my code:-
SqlConnection con = new SqlConnection(getconnectionstring());
SqlCommand cmd = new SqlCommand();
SqlCommand cmd1 = new SqlCommand();
//cmd.CommandText = "SELECT firstname,lastname FROM crudtable";
cmd.CommandText = "SELECT firstname,lastname FROM crudtable";
cmd1.CommandText = "SELECT firstname FROM crudtable";
cmd.Connection = con;
cmd1.Connection = con;
con.Open();
SqlDataReader reader ;
SqlDataReader reader1;
reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
FormView1.DataSource = reader;
FormView1.DataBind();
reader.Close();
reader1 = cmd1.ExecuteReader();
ddl.DataSource = reader1;
ddl.DataTextField = "firstname";
ddl.DataBind();
Thanks in advance.
SqlDataReader is a forward only reader.
Provides a way of reading a forward-only stream of rows from a SQL
Server database.
Once the data is read, you can't go back to read it again.
That is why you can't use the same reader as a data source for another control without calling ExecuteReader again.
If the number of rows you get is small, you can fetch the data into a DataSet and bind that to both.
SqlConnection conn = new SqlConnection(ConnectionString);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT firstname,lastname FROM crudtable";
da.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds);
conn.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
FormView1.DataSource = ds;
FormView1.DataBind();
ddl.DataSource = ds;
ddl.DataTextField = "firstname";
ddl.DataBind();
Once you have the data in your DataSet, you can decide which columns to Bind and show.
For the most streamlined version of binding in this case I would modify the code like so:
DataTable results = new DataTable();
using (SqlConnection connection = new SqlConnection(getconnectionstring()))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT firstname,lastname FROM crudtable",connection))
{
results.Load(command.ExecuteReader());
}
}
GridView1.DataSource = results;
GridView1.DataBind();
FormView1.DataSource = results;
FormView1.DataBind();
ddl.DataSource = results;
ddl.DataTextField = "firstname";
ddl.DataBind();
If 2 controls are not binding to 1 data source then take that data source and bind it to table then copy that table
And its data to another table and bind them seperatley.
DataTable.clone() will fetch the structure.
DatTable.Copy() will fetch schema and records
Clone reference
Copy Reference
Finally i took a new reader object to bind formview,but still it didn't work.Am i wrong somewhere or missing something.
Getting no exception no error.
This is updated code.
SqlConnection con = new SqlConnection(getconnectionstring());
SqlCommand cmd = new SqlCommand();
SqlCommand cmd1 = new SqlCommand();
SqlCommand cmd2 = new SqlCommand();
//cmd.CommandText = "SELECT firstname,lastname FROM crudtable";
cmd.CommandText = "SELECT firstname,lastname FROM crudtable";
cmd2.CommandText = "SELECT firstname,lastname FROM crudtable";
cmd1.CommandText = "SELECT firstname FROM crudtable";
cmd.Connection = con;
cmd1.Connection = con;
cmd2.Connection=con;
con.Open();
SqlDataReader reader ;
SqlDataReader reader1;
SqlDataReader reader2;
reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
reader.Close();
//reader.Close();
reader2 = cmd2.ExecuteReader();
FormView1.DataSource = reader2;
FormView1.DataBind();
reader2.Close();
reader1 = cmd1.ExecuteReader();
ddl.DataSource = reader1;
ddl.DataTextField = "firstname";
ddl.DataBind();
reader1.Close();

i want to use data reader & update statement at same time

here is code
String[] month=new String[12]{"January","February","March","April","May","June","July","August","September","Octomber","November","December"};
int day = DateTime.Now.Day;
int mon= DateTime.Now.Month;
mon = mon - 1; //because month array is with 0
Label1.Text = day.ToString();
if (day==21)
{
int j = 1;
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = MyConn;
cmd1.CommandText = "SELECT No_of_times,Dustbin_no from mounthly_data";
SqlDataReader MyReader = cmd1.ExecuteReader();
while (MyReader.Read())
{
String a = MyReader["No_of_times"].ToString();
String b = MyReader["Dustbin_no"].ToString();
SqlCommand cmd = new SqlCommand();
cmd.Connection = MyConn;
cmd.CommandText = "update Yearly_data set [" + month[mon] + "]='"+a+"' where Dustbin_no='"+b+"'"; //just see ["+month[mon+"] it's imp
i = cmd.ExecuteNonQuery();
}
MyReader.Close();
}
i got error as
There is already an open DataReader associated with this Command which must be closed first.
I think you should give us the rest of the code above this code block because I'm not sure how a ExecuteNonQuery is using up a datareader. But from what I can gather, what you probably want is to open two separate connections. Only one datareader can be open per connection at a time. Either you use two separate connections or you could maybe use a datatable/dataset for the result of both your queries.
EDIT: From the rest of your code, yes, using two connections would be the simplest answer. When a reader is open, the connection associated with it is dedicated to the command that is used, thus no other command can use that connection.
I would recommend using a DataTable as this OLEDB example shows:
public static void TrySomethingLikeThis()
{
try
{
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = Users.GetConnectionString();
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Customers";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.AsEnumerable())
{
cmd.CommandText = "UPDATE Customers SET CustomerName='Ronnie' WHERE ID = 4";
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

Resources