Asp.net dropdownlist and gridview

I created 2 DropdownList and 1 GridView

1st DropdownList Loads and Displays Database Names Dynamically

2nd DropdownList Loads and displays Table Names based on the name of the database that is selected in the first drop-down list

Based on the data in the table, Data should be displayed in the GridView ........

I wrote code that displays database names and works 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 the database tables should be displayed ..... how to pass the database name (which is selected in the first drop-down list) in the following code ..... This is the right way to pass the 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(); } 
+4
source share
3 answers

I'm not sure if this is required or not, but you have to specify the db name in the connection string. Database=Northwind; in this case, using the System.Data.SqlClient.SqlConnectionStringBuilder class is even better. And then you can request table names if the user has the correct rights.

0
source

I think you should include the database name in the connection string that you use to populate the 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

0
source

Try the following:

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

Source: https://habr.com/ru/post/1445738/


All Articles