I am entering the source name userid and password through the textbox and want the database list should be listed on the combo box so that all the four options sourcename, u
Simply using GetSchema
method:
using (SqlConnection connection = GetConnection())
{
connection.Open();
DataTable dtDatabases = connection.GetSchema("databases");
//Get database name using dtDatabases["database_name"]
}
you can use on of the following queries:
EXEC sp_databases
SELECT * FROM sys.databases
Serge
First add following assemblies:
from
C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\
and then use below code:
var server = new Microsoft.SqlServer.Management.Smo.Server("Server name");
foreach (Database db in server.Databases) {
cboDBs.Items.Add(db.Name);
}
How to get list of all database from sql server in a combobox using c# asp.net windows application
try
{
string Conn = "server=.;User Id=sa;" + "pwd=passs;";
SqlConnection con = new SqlConnection(Conn);
con.Open();
SqlCommand cmd = new SqlCommand();
// da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cmd = new SqlCommand("SELECT name FROM sys.databases", con);
// comboBox1.Items.Add(cmd);
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//comboBox2.Items.Add(dr[0]);
comboBox1.Items.Add(dr[0]);
}
}
// .Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
sys.databases
SELECT name
FROM sys.databases;
Edit:
I recommend using IDataReader, returning a List and caching the results. You can simply bind your drop down to the results and retrieve the same list from cache when needed.
public List<string> GetDatabaseList()
{
List<string> list = new List<string>();
// Open connection to the database
string conString = "server=xeon;uid=sa;pwd=manager; database=northwind";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
// Set up a command with the given query and associate
// this with the current connection.
using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con))
{
using (IDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
list.Add(dr[0].ToString());
}
}
}
}
return list;
}
using (var connection = new System.Data.SqlClient.SqlConnection("ConnectionString"))
{
connection.Open();
var command = new System.Data.SqlClient.SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT name FROM master.sys.databases";
var adapter = new System.Data.SqlClient.SqlDataAdapter(command);
var dataset = new DataSet();
adapter.Fill(dataset);
DataTable dtDatabases = dataset.Tables[0];
}