Click here to Skip to main content
16,017,638 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have two database in my sql server

(But this code gives only one database name)
my code was........what's wrong in it..


C#
SqlConnection con = new SqlConnection("Data source=Lenovo-Pc;Initial catalog=master;User ID=sa;Password=12345");
con.Open();
SqlCommand cmd = new SqlCommand("Select * From sys.databases Where database_id > 5", con);
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
        listBox1.Text = sdr["name"].ToString();
}
con.Close();
Posted
Updated 20-Feb-13 0:49am
v2
Comments
GopinathSk 20-Feb-13 6:53am    
k.but even it gives only one db name..

Change the "if" to a "while":
if (sdr.Read())
Becomes
while (sdr.Read())
And append the text to your listbox instead of overwriting it.


[edit]added my method for this - Original Griff[/edit]

Your code isn't the method I use, but it should work. The way I do it is:

C#
using (SqlConnection con = new SqlConnection(@"Data Source=GRIFFPC\SQLEXPRESS;Integrated Security=True"))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("sp_databases", con))
        {
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataReader read = cmd.ExecuteReader();
        while (read.Read())
            {
            Console.WriteLine((string)read["DATABASE_NAME"]);
            }
        }
    }
So a quick replacement of the security information with yours should make it work as well.

BTW: Change your admin login - you just told the entire world how to destroy your databases...
 
Share this answer
 
v2
Comments
CHill60 20-Feb-13 6:53am    
My 5 - but I'm still chuckling :-)
GopinathSk 20-Feb-13 6:55am    
y laughing.
GopinathSk 20-Feb-13 6:54am    
what would be initial catalog.
OriginalGriff 20-Feb-13 6:57am    
Sorry? Which initial catelog are you asking for?
GopinathSk 20-Feb-13 7:00am    
SqlConnection con = new SqlConnection("Data source=Lenovo-Pc;Initial catalog=master;User ID=sa;Password=12345");


is it right to achieve the list of db's name
You are using Listbox1.Text
This is from the Listbox Metadata (underlining mine)
//
// Summary:
//     Gets or searches for the text of the currently selected item in the System.Windows.Forms.ListBox.
//
// Returns:
//     The text of the currently selected item in the control.

To list all of the databases in your listbox you should be adding to the items collection i.e.
listBox1.Items.Add(sdr["name"]);

or use a multi-line Text box
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900