Can i bind same datareader object to 2 controls? - asp.net

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();

Related

How to display data on label using stored procedure

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"]);
}
}

I want my table to display all record if no searches were found for a movie but am unsure how to do that

This is my code, tell me where to change because When I do search for a movie that is in a record it displays the result, but when it isn't I only get "Movie Not Found" as in the response.write.
enter image description hereSLNkq.png
I would suggest to put question as text/code instead.
For your case, I suggest you to work with datatable instead of datareader.
== With Datatable approach ==
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("IF EXISTS(SELECT * FROM Content WHERE MovieTitle=#MovieTitle) SELECT * FROM Content WHERE MovieTitle=#MovieTitle ELSE SELECT * FROM Content");
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#MovieTitle", MovieTitle.Text);
cmd.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Result");
da.Fill(dt);
con.Close();
MovieResults.DataSource = dt;
MovieResults.DataBind();
Based on #Shai Cohen's comment, it would be better approach by using ExecuteDataReader if transaction is forward-only. Thanks #ShaiCohen for your comment.
== Without Datatable approach ==
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("IF EXISTS(SELECT * FROM Content WHERE MovieTitle=#MovieTitle) SELECT * FROM Content WHERE MovieTitle=#MovieTitle ELSE SELECT * FROM Content");
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#MovieTitle", MovieTitle.Text);
cmd.Connection = con;
con.Open();
MovieResults.DataSource = cmd.ExecuteReader();
MovieResults.DataBind();
con.Close();
Enjoy Coding (;

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();

Detailsview in ASP.NET

I am trying to hit sql server with objectdatasource and return a datatable to fill my details view control. the selected ID value is returned by a gridview control. It seems like the datatable is not filled by adapter, and i couldn't figure out why. The ID in sql is set as a primary key (Int, 4, not null). The debugger says the Detail datatable is null. Any help is much appreciated.
public DataTable GetDetail(string ID)
{
if (ID == "")
{
return null;
}
else
{
DataTable Detail = null;
using (SqlConnection conn = new SqlConnection(connection))
{
string comm = #"select * from dbo.Products where ID = #ID";
conn.Open();
SqlDataAdapter adapter=null;
using (SqlCommand cmd = new SqlCommand(comm, conn))
{
cmd.Parameters.Add("ID", System.Data.SqlDbType.Int, 4).Value = Convert.ToInt32(ID);
adapter = new SqlDataAdapter(cmd);
adapter.Fill(Detail);
return Detail;
}
}
}
I think you missed the commandType
cmd.CommandType = CommandType.Text;
Try this
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(connection))
{
string myquery="select * from dbo.Products where ID = #ID";
SqlCommand cmd = new SqlCommand(myquery, con);
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = cmd;
cmd.Parameters.Add("#ID", SqlDbType.NVarChar, 15).Value = ID;
dap.Fill(ds);
return ds.Tables[0];
}
Thanks for ALL.
The problem is I didnt initialize my datatable to a new instance.
DataTable Detail = null; ===> DataTable Detail = new Datatable();
and also the convert should be done in sql not in codes.
cmd.Parameters.Add("ID", System.Data.SqlDbType.Int, 4).Value = ID;
string comm = #"select * from dbo.Products where ID = convert(int,#ID)";

Resources