I Inserted Data to ComboBox using Folloowing Code in FormLoad Block
try
{
using (SqlConnection con = new SqlConnection(conString))
{
SelectCategoryComboBox.Items.Clear();
string query = "SELECT CategoryName FROM CategoryTable";
con.Open();
SqlDataReader sdr = new SqlCommand(query, con).ExecuteReader();
while (sdr.Read())
{
SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
}
}
}
catch
{
StatusLabel.Text = "An error occured while loading Data";
}
finally
{
SelectCategoryComboBox.SelectedItem = null;
SelectCategoryComboBox.SelectedText = "Choose Category";
}
it does the Job. in the Form You can Create a Category and Delete By Selecting The Name of the category from ComboBox Here is a ScreenShot the Form. I used the following code to Delete and Load the items to ComboBox after Deleting.
try
{
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
String query = "DELETE FROM CategoryTable WHERE CategoryName='" + SelectCategoryComboBox.SelectedItem.ToString() + "'";
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
}
StatusLabel.Text = "You have successfully deleted " + SelectCategoryComboBox.SelectedItem.ToString() + " Category";
}
catch
{
StatusLabel.Text = "An Error occured while deleting " + SelectCategoryComboBox.SelectedItem.ToString() + " Category";
}
finally
{
try
{
SelectCategoryComboBox.Items.Clear();
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
string query = "SELECT CategoryName FROM CategoryTable";
con.Open();
SqlDataReader sdr = new SqlCommand(query, con).ExecuteReader();
while (sdr.Read())
{
SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
}
}
}
catch
{
StatusLabel.Text = "An error occured while loading Data";
}
finally
{
SelectCategoryComboBox.SelectedItem = null;
SelectCategoryComboBox.SelectedText = "Choose Category";
}
code for Creating new item Given below
if (CategoryNameText.Text == "")
{
StatusLabel.Text = "You have to provide a name to create a category";
}
else
{
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
String query = "INSERT INTO CategoryTable(CategoryName) VALUES('" + CategoryNameText.Text + "')";
try
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
}
StatusLabel.Text = "You have successfully created " + CategoryNameText.Text + " Category";
try
{
using (SqlConnection scon = new SqlConnection(conString))
{
string locQuery = "SELECT CategoryName,Categoryid FROM CategoryTable";
SqlDataAdapter da = new SqlDataAdapter(locQuery, scon);
scon.Open();
DataSet ds = new DataSet();
da.Fill(ds, "CategoryTable");
SelectCategoryComboBox.ValueMember = "Categoryid";
SelectCategoryComboBox.DisplayMember = "CategoryName";
SelectCategoryComboBox.DataSource = ds.Tables["CategoryTable"];
}
}
catch
{
Thread.Sleep(3000);
StatusLabel.Text = "An Error Occured while Loading Data!";
}
finally
{
SelectCategoryComboBox.SelectedItem = null;
SelectCategoryComboBox.SelectedText = "Choose Category";
}
CategoryNameText.Focus();
}
catch
{
Thread.Sleep(3000);
StatusLabel.Text = ("An ERROR occured While creating category!");
}
finally
{
CategoryNameText.Text = "Enter Category Name";
}
}
}
This Code Deletes Items Perfectly.But If I delete an Item Which is Already in the ComboBox, it does the Job i.e it deletes and Load the Remaining items to ComboBox.but, if I Created an Item,and Deleted it Before Closing the Form, it deletes the item.But Fails to Load the remaining items.it shows all the items already exist in the ComboBox Before Deleting. Would be a great help if you can help me solve this problem. Here SelectCategoryComboBox is the Name of the ComboBox.
I find the problem occur in the following sentence.
String query = "INSERT INTO CategoryTable(CategoryName) VALUES('" + CategoryNameText.Text + "')";
I have two solutions.
First, Please set the Allow nulls for other field.
Like the following:
Second, you can use the following code to replace the original code.
string query = string.Format("INSERT INTO Student(CategoryName, CategoryId, Age) VALUES('{0}','{1}','{2}')",textBox1.Text,textBox2.Text,textBox3.Text);
I found What went Wrong...
Change Following Code
using (SqlConnection scon = new SqlConnection(conString))
{
string locQuery = "SELECT CategoryName,Categoryid FROM CategoryTable";
SqlDataAdapter da = new SqlDataAdapter(locQuery, scon);
scon.Open();
DataSet ds = new DataSet();
da.Fill(ds, "CategoryTable");
SelectCategoryComboBox.ValueMember = "Categoryid";
SelectCategoryComboBox.DisplayMember = "CategoryName";
SelectCategoryComboBox.DataSource = ds.Tables["CategoryTable"];
}
To
using (SqlConnection con = new SqlConnection(conString))
{
SelectCategoryComboBox.Items.Clear();
string squery = "SELECT CategoryName FROM CategoryTable";
con.Open();
SqlDataReader sdr = new SqlCommand(squery, con).ExecuteReader();
while (sdr.Read())
{
SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
}
}
it Worked for me.
Related
private void filljobid()
{
try
{
string jobid = "";
int newjobid, oldjobid;
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand("SELECT MAX(job_id) FROM job", con);
SqlDataReader reader;
reader = cmd.ExecuteReader();
while (reader.Read())
{
jobid = reader[0].ToString();
}
oldjobid = int.Parse(jobid.ToString());
newjobid = oldjobid + 1;
jobidtextbox.Text = newjobid.ToString();
}
catch (Exception)
{
MessageBox.Show("Error while connecting");
}
}
private void fillcustomercombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT customer_id,(first_name + ' ' + last_name + ' - ' + contact) AS CUSTOMERNAME FROM customer", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
customeridcombobox.DataSource = ds.Tables[0];
customeridcombobox.DisplayMember = "CUSTOMERNAME";
customeridcombobox.ValueMember = "customer_id";
cmd.ExecuteReader();
con.Close();
// CODE FOR DISPLAYING multiple values in another way, but not sure how to retrieve data from this function
// for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
// {
// customeridcombobox.Items.Add(ds.Tables[0].Rows[i][0] + " - " + ds.Tables[0].Rows[i][1] + " " + ds.Tables[0].Rows[i][2]);
// }
}
private void filldepotcombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT depot_id,(branch_name + ' - ' + region_name + ' - ' + location) AS DEPOTNAME FROM depot", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
depotidcombobox.DataSource = ds.Tables[0];
depotidcombobox.DisplayMember = "DEPOTNAME";
depotidcombobox.ValueMember = "depot_id";
cmd.ExecuteReader();
con.Close();
}
private void filljobtypecombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT job_type FROM jobtype", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
jobtypecombobox.DisplayMember = "job_type";
jobtypecombobox.ValueMember = "job_type";
jobtypecombobox.DataSource = ds.Tables[0];
cmd.ExecuteReader();
con.Close();
}
private void loadingcomboboxesdata_Load(object sender, EventArgs e)
{
fillcustomercombox();
filljobid();
filldepotcombox();
filljobtypecombox();
}
private void addnewjobbutton_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMoversDB;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into job (start_location, end_location, depot_id, job_type, customer_id,) values ('" + startlocationtxtbox.Text + "','" + endlocationtxtbox.Text + "','" + depotidcombobox.Text + "','" + jobtypecombobox.Text + "','" + customeridcombobox.Text + "')";
cmd.ExecuteReader();
con.Close();
MessageBox.Show("Added new job");
}
catch (Exception)
{
MessageBox.Show("ERROR: CANNOT CONNECT TO DATABASE");
}
}
What I'm trying to achieve is basically take the users selected value which is displayed in the combo box which is valuemember and then insert it into the database. Right now I get the error when I try to insert the data into the database. When I do the combo box with a single value it works fine but it doesn't work when I do it with multiple values.
Could someone close this question. I managed to solve my own question. I dont know if this solution is considered good but here you go.
private void addnewjobbutton_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True"))
{
try
{
using (var cmd = new SqlCommand("INSERT INTO job(start_location, end_location, depot_id, job_type, customer_id) VALUES ('" + startlocationtxtbox.Text + "','" + endlocationtxtbox.Text + "',#3,#4, #5)"))
{
cmd.Connection = con;
//cmd.Parameters.AddWithValue("#1", startlocationtxtbox.SelectedText);
//cmd.Parameters.AddWithValue("#2", endlocationtxtbox.SelectedText);
cmd.Parameters.AddWithValue("#3", depotidcombobox.SelectedValue);
cmd.Parameters.AddWithValue("#4", jobtypecombobox.SelectedValue);
cmd.Parameters.AddWithValue("#5",customeridcombobox.SelectedValue);
con.Open();
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception)
{
MessageBox.Show("ERROR: CANNOT CONNECT TO DATABASE");
}
}
}
I want insert some data to localdatabace and insert is successfully done but don't show in my datagridview tile second insert do for debog it I Call Select All end of my insert and see the last insert don't show in it but whene i insert a next data , last data will be showing can every one help me pleas?
public void connect()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(conString);
String sqll = "Insert into TblBank (txtTodayDate" +
",txtSahebanHesab" +
",txtShobe" +
",txtShomareMoshtari" +
",txtShoareHesab" +
",cmbNoeHesab" +
",txtSarresid" +
")";
try
{
sql.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqll, sql);
SqlCommand sc = new SqlCommand(sqll,sql);
sc.Parameters.AddWithValue("todayDate", new PersianDateTime(dtpTodayDate.the_date).ToString("yyyy/MM/dd"));
sc.Parameters.AddWithValue("sahebanHesab", txtSahebHesabName.Text);
sc.Parameters.AddWithValue("shobe", txtshobe.Text);
sc.Parameters.AddWithValue("shomareMoshtari", txtShomareMoshtari.Text);
sc.Parameters.AddWithValue("shoareHesab", txtShomareHesab.Text);
sc.Parameters.AddWithValue("noeHesab", cmbNoeHesab.SelectedIndex);
sc.Parameters.AddWithValue("sarresid", txtSarResidMah.Text);
sc.ExecuteNonQuery();
sql.Close();
select();
}
catch (Exception ex)
{
}
}
and select is
private void select()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection cn = new SqlConnection(conString);
String sqlString = "SELECT * FROM TblBank Order BY Id desc ";
SqlConnection sql = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(sqlString, cn);
try {
sql.Open();
SqlDataAdapter sa = new SqlDataAdapter(sqlString, sql);
using (SqlDataReader read = sa.SelectCommand.ExecuteReader())
{
if (read.Read())
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
sql.Close();
}
catch (Exception ex)
{
}
}
The DataReader.Read() method will iterate result set before DataTable.Load(). Because the DataReader is a forward-only stream, it has empty result set when DataTable.Load() executes and DataTable content is still empty while setting DataSource for DataGridView. Try DataReader.HasRows property to check result set availability:
using (SqlConnection cn = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(sqlString, cn))
{
try
{
cn.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
// check if the reader returns result set
if (read.HasRows)
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
}
catch (Exception ex)
{
// do something
}
}
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
con = new SqlConnection("Data Source = LENOVO; Initial Catalog = MainData; Integrated Security = True");
con.Open();
string CheckID = "select StaffID from PersonsData where StaffID='" + txtStaffID.Text + "'";
cm = new SqlCommand(CheckID);
SqlDataReader rdr = null;
rdr = cm.ExecuteReader();
if (rdr.Read())
{
MessageBox.Show("Company Name Already Exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtStaffID.Text = "";
txtStaffID.Focus();
}
else
{
byte[] img = null;
FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
string Query = "insert into PersonsData (StaffID, FullName, Email, Address, Picture) values('" + this.txtStaffID.Text + "','" + this.txtFullname.Text + "','" + this.txtEmail.Text + "','" + this.txtAddress.Text + "',#img)";
if (con.State != ConnectionState.Open)
con.Open();
cm = new SqlCommand(Query, con);
cm.Parameters.Add(new SqlParameter("#img", img));
int x = cm.ExecuteNonQuery();
con.Close();
MessageBox.Show(x.ToString() + "Successfully Saved!");
}
}
catch (Exception ex)
{
con.Close();
MessageBox.Show(ex.Message);
}
}
This is my code i don't understand why I'm getting this error:
ExecuteReader:Connection Property has not been initialized.
I'm making a save button where the Staffid will be checked first if already.
Before executing the command, you need to say which connection is to be used. In your case, it is:
cm.Connection = con;
Take a note that, include this line of code after opening the connection and after creating the instance of SqlCommand.
con = new SqlConnection("Data Source = LENOVO; Initial Catalog = MainData; Integrated Security = True");
con.Open();
string CheckID = "select StaffID from PersonsData where StaffID='" + txtStaffID.Text + "'";
cm = new SqlCommand(CheckID);
cm.Connection = con; //Assign connection to command
You didn't assign connection to SqlCommand used in the reader
The error message is clear enough, You have to assign the connection for the Command, either through assignement or through the constructor, That is:
cm = new SqlCommand(CheckID);
cm.Connection = con; // Should be added
SqlDataReader rdr = cm.ExecuteReader();
Or else you can use the constructor to initialize the command like this:
cm = new SqlCommand(CheckID,con);
Hope that you are aware of these things since you ware used it correctly in the else part of the given snippet
Make sure that you assign the SqlConnection to your Command-Object. You can do this via Constructor or Property:
con = new SqlConnection(//Your Connectionstring)
//assign via Constructor
cm = new SqlCommand(CheckID, con);
//or via Property
cm.Connection = con;
SqlDataReader rdr = null;
rdr = cm.ExecuteReader();
Further I would recommend you to use a using-block to make sure that the Command and Connection gets destroyed after using it.
using (var con = new SqlConnection())
{
using (var cm = new SqlCommand())
{
}
}
I have a dropdownlist item named IsAuthor. It do not fill my textboxes by retrieving value from tblnewgroup table. Where is the problem I can not understand and it do not show any error please help me
protected void lstAuthor_SelectedIndexChanged(object sender, EventArgs e)
{
string selectSQL;
selectSQL = "SELECT * FROM tblnewgroup ";
selectSQL += "WHERE Groupno='" + lstAuthor.SelectedItem.Value + "'";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Read();
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
reader.Close();
lblResults.Text = "";
}
catch (Exception err)
{
lblResults.Text = "Error getting author. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
I filled my drop down list by these codes..
private void FillAuthorList()
{
lstAuthor.Items.Clear();
string selectSQL = "SELECT Groupname, Groupno FROM tblnewgroup";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem = new ListItem();
newItem.Text = reader["Groupname"].ToString();
newItem.Value = reader["Groupno"].ToString();
lstAuthor.Items.Add(newItem);
}
reader.Close();
}
catch (Exception err)
{
lblResults.Text = "Error reading list of names. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
Problem : you are assigning single quotes to number feild Groupno.
Solution : you need to assign single quotes to VARCHAR Types only.
Suggestion: you are just assigning the values from SqlDataReader object without checking for rows.if the rows are not found then it will throw the Exeption. So i would suggest to Ceck the SqlDataReader object for any rows before assigning the values to TextBox Controls.
Try This:
protected void lstAuthor_SelectedIndexChanged(object sender, EventArgs e)
{
string selectSQL;
selectSQL = "SELECT * FROM tblnewgroup ";
selectSQL += "WHERE Groupno=" + lstAuthor.SelectedValue;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
if(reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
lblResults.Text = "Data Updated Successfully!";
}
else
{
lblResults.Text = "No Records found!";
}
reader.Close();
}
catch (Exception err)
{
lblResults.Text = "Error getting author. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
It looks like you're selecting on a number field, but treating it like a text field. Modify your query to remove the single quotes:
selectSQL = "SELECT * FROM tblnewgroup ";
selectSQL += "WHERE Groupno=" + lstAuthor.SelectedItem.Value;
Also check the return value of reader.read() to see if there are any records:
using(var reader = cmd.ExecuteReader())
{
if(reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
}
else
{
lblResults.Text = "Author not found";
}
}
Note that I've put the reader in a using block to ensure it is closed, even if an exception occurs.
I assume SqlDataReader.Read method returns boolean value and you can use it like;
while(reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
}
Also I suspect lstAuthor.SelectedItem.Value is a number instead of a string. You might need to use it without using "".
Also using parameterized queries always a good choice.
selectSQL = "SELECT * FROM tblnewgroup WHERE Groupno = #Groupno";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("#Groupno", lstAuthor.SelectedItem.Value);
....
Use following:
while (reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
}
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, userid, password and databasename can be selected by the user to perform the connectivity
The databases are to be retrieve from other system as per the user. User will enter the IP, userid and password and they should get the database list in the combo box so that they can select the required database and perform the connectivity
private void frmConfig_Load(object sender, EventArgs e)
{
try
{
string Conn = "server=servername;User Id=userid;" + "pwd=******;";
con = new SqlConnection(Conn);
con.Open();
da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cbSrc.Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am trying to do this but it is not generating any data
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;
}
First add following assemblies:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
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);
}
you can use on of the following queries:
EXEC sp_databases
SELECT * FROM sys.databases
Serge
Simply using GetSchema method:
using (SqlConnection connection = GetConnection())
{
connection.Open();
DataTable dtDatabases = connection.GetSchema("databases");
//Get database name using dtDatabases["database_name"]
}
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];
}
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);
}
Try this:
SqlConnection con = new SqlConnection(YourConnectionString);
SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbSrc.Items.Add(dr[0].ToString());
}
con.Close();
or this:
DataSet ds = new DataSet();
SqlDataAdapter sqlda = new SqlDataAdapter("SELECT name from sys.databases", YourConnectionString);
sqlda.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
cbSrc.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}
public static List<string> GetAllDatabaseNamesByServerName(string ServerName, [Optional] string UserID, [Optional] string Password)
{
List<string> lstDatabaseNames = null;
try
{
lstDatabaseNames = new List<string>();
//string servername = System.Environment.MachineName;
string newConnString = string.Format("Data Source={0};", ServerName);
if (UserID == null)
{
newConnString += "Integrated Security = True;";
}
else
{
newConnString += string.Format("User Id ={0}; Password={1};", UserID, Password);
}
SqlConnection con = new SqlConnection(newConnString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT name FROM master.sys.databases", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
lstDatabaseNames.Add(row[0].ToString());
}
con.Close();
return lstDatabaseNames;
}
finally
{
}
}