asp.net dropdownlist and gridview - asp.net

I have created 2 DropdownList and 1 GridView
1st DropdownList Loads and Displays DataBase Names Dynamically
2nd DropdownList Loads and Displays Table Names, Based on Database name Which selected in 1st drop down list
Based on Table Name Data has to be displayed in GridView........
I have written code which displays Database Names and working fine
private void populateDatabasename() {
SqlConnection con = new SqlConnection(#"Data Source=SAI- PC\SQLEXPRESS;Integrated Security=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select name,collation_name from sys.databases order by name", con);
DataSet ds = new DataSet();
da.Fill(ds, "dbname");
DropDownList1.DataSource = ds.Tables["dbname"];
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "name";
DropDownList1.DataBind();
}
Based on Database name tables have to be displayed..... how to pass Database name(Which is selected in 1st drop down list) in the following code.....
Is This a correct way to pass database name
private void populateTableName() {
SqlConnection con = new SqlConnection(#"Data Source=SAI-PC\SQLEXPRESS;Integrated Security=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select name from "+"#Dbname"+".sys.tables", con);
da.SelectCommand.Parameters.Add("#dbname", SqlDbType.VarChar);
da.SelectCommand.Parameters["#dbname"].Value = DropDownList1.SelectedValue;
DataSet ds = new DataSet();
da.Fill(ds, "dbname1");
DropDownList2.DataSource = ds.Tables["dbname1"];
DropDownList2.DataTextField = "name";
DropDownList2.DataValueField = "name";
DropDownList2.DataBind();
}

I am not sure if it required or not but you should give the db name in connection string. Database=Northwind; in this case, using System.Data.SqlClient.SqlConnectionStringBuilder class even better. And then you can query the table names if the user have correct rights.

i think you should include DataBase name in connection string that you use to populate table
use something like this
SqlConnection con = new SqlConnection(#"Data Source=SAI-PC\SQLEXPRESS;Database=" + Dropdownlist1.selecteditem.text + ";Integrated Security=True");
then Read the tables and continue

Try this:
string dbName = ddlDbName.SelectedValue;
string strcon = "server=SAI-PC\\SQLEXPRESS;database= " + dbName + ";providerName=\"System.Data.SqlClient\"";
SqlConnection con = new SqlConnection(strcon);
con.Open();

Related

Must declare the scalar variable "#Sid" in gridview while getting single record

while i'm trying to get single record from database table,based on login user details. i'm getting error,let me know where i'm doing wrong.
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
SqlConnection cn = new SqlConnection((cs));
cn.Open();
SqlCommand cmd = new SqlCommand("select * from Student_Details where Sid=#Sid", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
GridView1.DataBind();
Why you are executing query for select statement - cmd.ExecuteNonQuery(); not require..
You have to pass parameter value also
cmd.Parameters.AddWithValue("#sid", sid);
you missed this lines:
cmd.Parameters.AddWithValue("sid", User.Identity.Name)
and also cmd.ExecuteNonQuery(); is not necessary.

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

How can I use DataTextField on an element that is not a ListControl?

So here's my situation: I have a DropDownList that I populate when a certain event is triggered. To populate it, I execute a SQL query that returns two columns: ID and Name. I bind the Name to the DropDownList using DataSource/DataTextField/DataValueField, but I want to save the ID as well (to use in a second query). How can I do this?
I have tried saving the ID to a hidden input field, because I want to use it but not display it to the user. But input is not a ListControl, so it doesn't work. How do I get the matching ID of the Name selected in the DropDownList?
string strConn = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Id, Name FROM Users WHERE Age > 10";
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
NameDropDown.DataSource = objDs.Tables[0];
NameDropDown.DataTextField = "Name";
NameDropDown.DataValueField = "Name";
NameDropDown.DataBind();
NameDropDown.Items.Insert(0, "--Select--");
}
else
{
NameDropDown.Items.Clear();
NameDropDown.Items.Insert(0, "No names found");
}
Consider:
if (objDs.Tables[0].Rows.Count > 0)
{
NameDropDown.DataSource = objDs.Tables[0];
NameDropDown.DataTextField = "Name";
NameDropDown.DataValueField = "ID"; /*why wouldn't this be ID*/
NameDropDown.DataBind();
NameDropDown.Items.Insert(0, "--Select--");

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

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

Resources