ComboBox cannot display new value added - c#

I have added a new value into my combobox and it should be displayed based on what I have in my database. But unfortunately, the new value does not display out. Below are my codes.
string dbConn = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\SONY\\Desktop\\FinalYearProject\\FinalYearProject\\bin\\Debug\\housewife.mdf;Integrated Security=True;User Instance=True";
void fill_Combo() {
SqlConnection conn = new SqlConnection(dbConn);
try {
conn.Open();
string query = "Select * From Food";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
string name = dr.GetString(1);
comboBox1.Items.Add(name);
}
conn.Close();
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
}

You should be using an observable collection as the data source and binding to that collection. See Add items to comboBox in WPF

Hi please try something like this, hope it helps
string dbConn = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\SONY\\Desktop\\FinalYearProject\\FinalYear Project\\bin\\Debug\\housewife.mdf;Integrated Security=True;User Instance=True";
void fill_Combo() {
SqlConnection conn = new SqlConnection(dbConn);
try {
conn.Open();
string query = "Select * From Food";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds)
combobox1.DataSourse = ds;
combobox1.DisplayMember = "fieldname";
combobox1.ValueMember = "fieldname";
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
}

Related

dropdownlist is not showing the selecteditem from the database

am trying to get the selected item from the database, but its not displaying nothing
code behind:
private void bindRows()
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MainConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand cmd = new SqlCommand("select id, message from Dropdown", connection);
SqlDataReader reader = cmd.ExecuteReader();
reader.Close();
SqlDataAdapter adapter = new SqlDataAdapter("select id, message from Dropdown", connection);
DataSet ds = new DataSet();
adapter.Fill(ds);
DdlRegister.DataSource = ds;
DdlRegister.DataTextField = "message";
DdlRegister.DataValueField = "id";
DdlRegister.DataBind();
DdlRegister.Items.Insert(0, new ListItem("I Want", "0"));
connection.Close();
}
catch (Exception e)
{
}
}
code of buttonclick
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MainConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string selectCommand = "Insert into Register (name,designation,company,mobile,email,message) values(#name,#designation,#company,#mobile,#email,#message);";
SqlCommand cmd = new SqlCommand(selectCommand, connection);
cmd.Parameters.AddWithValue("#name", txtname.Text.Trim());
cmd.Parameters.AddWithValue("#designation", txtdesignation.Text.Trim());
cmd.Parameters.AddWithValue("#company", txtcompany.Text.Trim());
cmd.Parameters.AddWithValue("#mobile", txtmobile.Text.Trim());
cmd.Parameters.AddWithValue("#email", txtemail.Text.Trim());
cmd.Parameters.AddWithValue("#message", DdlRegister.SelectedItem.Text.Trim());
int cnt = cmd.ExecuteNonQuery();
if (cnt > 0)
{
ShowMessage("Registeration is done");
}
Response.Redirect("Index.aspx");
connection.Close();
}
catch (Exception ex)
{
}
design
<asp:DropDownList ID="DdlRegister" runat="server" CssClass="form-control ddl " OnSelectedIndexChanged="DdlRegister_SelectedIndexChanged" AutoPostBack="true" >
</asp:DropDownList>
private void bindRows()
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MainConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter("select id, message from Dropdown", connection);
DataSet ds = new DataSet();
adapter.Fill(ds);
DdlRegister.DataSource = ds;
DdlRegister.DataTextField = "message";
DdlRegister.DataValueField = "id";
DdlRegister.DataBind();
DdlRegister.Items.Insert(0, new ListItem("I Want", "0"));
connection.Close();
}
catch (Exception e)
{
}
}
try something like this
string mainconn = ConfigurationManager.ConnectionStrings["MY"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[sortcompany]";
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlconn.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sda.Fill(dt);
Company.ValueMember = "company_name";
Company.DisplayMember = "company_name";
Company.DataSource = dt;

What is the way to populate a dropdownlist from a database in asp.net by using classes?

I am trying to populate a dropdownlist from sql server by using classes as shown below. The code breaks down when it comes to bind the data into the dropdown list. It gives an error on giving the dropdownlist the dataValueField and datatTextField.
HTML... a.aspx
<asp:DropDownList ID="NationalityDropDownList" runat="server" >
</asp:DropDownList>
C#... a.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Classes.Nationality PossibleNationality = new Classes.Nationality();
if (!Page.IsPostBack)
{
DataTable dataTable = PossibleNationality.getNationality();
NationalityDropDownList.DataSource = dataTable;
NationalityDropDownList.DataValueField = "ID";
NationalityDropDownList.DataTextField = "Nationality";
NationalityDropDownList.DataBind();
}
}
Nationality.cs
public class Nationality
{
public DataTable getNationality()
{
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["InformationConnection"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("spGetAllUsers", conn);
comm.CommandType = CommandType.StoredProcedure;
DataTable dataTable;
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
dataTable = new DataTable();
da.Fill(dataTable);
}
finally
{
conn.Close();
}
return dataTable;
}
}
SQL procedure....
ALTER PROCEDURE [dbo].[spGetNationalities]
AS
BEGIN
select * from Nationality;
END
This line of code in your getNationalitymethod...
comm = new SqlCommand("spGetAllUsers", conn);
...should be this instead
comm = new SqlCommand("spGetNationalities", conn);
Databinding should work if your Nationality table has columns ID and Nationality
if (!Page.IsPostBack)
{
try
{
using (SqlConnection con = new SqlConnection("Data Source = NIPOON; Initial Catalog = CustomerOrders; Integrated Security = true"))
{
SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
con.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "Name";
dropDownList.DataValueField = "Name";
dropDownList.DataBind();
}
}
catch (Exception Ex)
{
Console.WriteLine("Error: " + Ex.Message);
}
GetData();
}

Populate a datagridview with sql query results

I'm trying to present query results, but I keep getting a blank data grid.
It's like the data itself is not visible
Here is my code:
private void Employee_Report_Load(object sender, EventArgs e)
{
string select = "SELECT * FROM tblEmployee";
Connection c = new Connection();
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, c.con); //c.con is the connection string
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
What's wrong with this code?
Here's your code fixed up. Next forget bindingsource
var select = "SELECT * FROM tblEmployee";
var c = new SqlConnection(yourConnectionString); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
String strConnection = Properties.Settings.Default.BooksConnectionString;
SqlConnection con = new SqlConnection(strConnection);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from titles";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.DataSource = dtRecord;
You don't need bindingSource1
Just set dataGridView1.DataSource = table;
Try binding your DataGridView to the DefaultView of the DataTable:
dataGridView1.DataSource = table.DefaultView;
This is suppose to be the safest and error pron query :
public void Load_Data()
{
using (SqlConnection connection = new SqlConnection(DatabaseServices.connectionString)) //use your connection string here
{
var bindingSource = new BindingSource();
string fetachSlidesRecentSQL = "select top (50) * from dbo.slides order by created_date desc";
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(fetachSlidesRecentSQL, connection))
{
try
{
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
bindingSource.DataSource = table;
recent_slides_grd_view.ReadOnly = true;
recent_slides_grd_view.DataSource = bindingSource;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString(), "ERROR Loading");
}
finally
{
connection.Close();
}
}
}
}
You may get a blank data grid if you set the data Source to a Dataset that you added to the form but is not being used. Set this to None if you are programatically setting your dataSource based on the above codes.
You may try this sample, and always check your Connection String, you can use this example with or with out bindingsource you can load the data to datagridview.
private void Employee_Report_Load(object sender, EventArgs e)
{
var table = new DataTable();
var connection = "ConnectionString";
using (var con = new SqlConnection { ConnectionString = connection })
{
using (var command = new SqlCommand { Connection = con })
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
try
{
command.CommandText = #"SELECT * FROM tblEmployee";
table.Load(command.ExecuteReader());
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
catch(SqlException ex)
{
MessageBox.Show(ex.Message + " sql query error.");
}
}
}
}
you have to add the property Tables to the DataGridView Data Source
dataGridView1.DataSource = table.Tables[0];
if you are using mysql this code you can use.
string con = "SERVER=localhost; user id=root; password=; database=databasename";
private void loaddata()
{
MySqlConnection connect = new MySqlConnection(con);
connect.Open();
try
{
MySqlCommand cmd = connect.CreateCommand();
cmd.CommandText = "SELECT * FROM DATA1";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
datagrid.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Years late but here's the simplest for others in case.
String connectionString = #"Data Source=LOCALHOST;Initial Catalog=DB;Integrated Security=true";
SqlConnection cnn = new SqlConnection(connectionString);
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblEmployee;", cnn);
DataTable data = new DataTable();
sda.Fill(data);
DataGridView1.DataSource = data;
Using DataSet is not necessary and DataTable should be good enough. SQLCommandBuilder is unnecessary either.
I think this professional way to Write from start, but you can use this code with MySQL bout I think they both are the same:
1/
using System.Data; AND using MySql.Data.MySqlClient;
2/
MySqlConnection con = new MySqlConnection("datasource=172.16.2.104;port=3306;server=localhost;database=DB_Name=root;password=DB_Password;sslmode=none;charset=utf8;");
MySqlCommand cmd = new MySqlCommand();
3/
public void SetCommand(string SQL)
{
cmd.Connection = con;
cmd.CommandText = SQL;
}
private void FillGrid()
{
SetCommand("SELECT * FROM `transport_db`ORDER BY `id` DESC LIMIT 15");
DataTable tbl = new DataTable();
tbl.Load(cmd.ExecuteReader());
dataGridView1.DataSource = tbl;
}
for oracle:
var connString = new ConfigurationBuilder().AddJsonFile("AppSettings.json").Build()["ConnectionString"];
OracleConnection connection = new OracleConnection();
connection.ConnectionString = connString;
connection.Open();
var dataAdapter = new OracleDataAdapter("SELECT * FROM TABLE", connection);
var dataSet = new DataSet();
dataAdapter.Fill(dataSet);

How to get data from SQL database to store in combo box - C#

How can i get the value of company_name from Comp table and store it on a comboBox?
here is my initial code on getting the values from Database and store it on a combobox:
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
it point out to da.fill(ds) and says "Could not locate entry in sysdatabases for database 'select company_name from JO'. No entry found with that name. Make sure that the name is entered correctly."
hope for your reply thanks!
Use datareader it is much simpler \
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand(Sql, conn);
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
combobox1.Items.Add(DR[0]);
}
If you set up your connection string to be something of this sort:
string SqlConnectionString = "Data Source=[SERVER];Initial Catalog=[DATABASE];"
Then using that set up, you can set your string 'Sql' as:
string Sql = "select company_name from dbo.Comp";
This could be a possible set up you could use to read out the values.
using (SqlConnection saConn = new SqlConnection(this.ConnectionString))
{
saConn.Open();
string query = "select DBName from dbo.Company";
SqlCommand cmd = new SqlCommand(query, saConn);
using (SqlDataReader saReader = cmd.ExecuteReader())
{
while (saReader.Read())
{
string name = saReader.GetString(0);
combobox1.Add(name);
}
}
saConn.Close();
}
I would like to introduce you a very simple way to SQL data into a combobox as:
first you have a create a SQL table,
in C# platform drop a combobox and go to its property,
in the property menu click on "DataSource"
specify the database and table to load into combobox,
Note, the combobox name and table's row should be the same.
{
SqlConnection con =new SqlConnection("Data Source=Server_Name;Initial Catalog=Database_Name;integrated security=true");
SqlCommand cmd;
SqlDataReader dr;
private void CashMemoForm_Load(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("Select Column_Name From Table_Name", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr[0]).ToString();
}
}
}
Have you ever tried Entity Framework for database access and dto creation?
Change your line to cmd.CommandType = CommandType.Text; instead of cmd.CommandType = CommandType.StoredProcedure;
Try this
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("--Select--", "0"));
}
There is no use of for loop. you just need to check that whether the dataset contains rows or not.
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("Select", "0"));
}
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
public System.Data.DataTable EmployeeViewAll()
{
DataTable dtbl = new DataTable();
try
{
// Here it shuld be your database Connection String
string connectionString = "Server = .; database = HKS; Integrated Security = true";
using (SqlConnection sqlCon = new System.Data.SqlClient.SqlConnection(connectionString))
{
SqlDataAdapter SqlDa = new SqlDataAdapter("employeeViewAll", sqlCon);
SqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlDa.Fill(dtbl);
}
return dtbl;
}
catch (Exception)
{
throw;
}
}
public void ComboFill()
{
DataTable dt = new DataTable();
eSP SP = new eSP();
d = SP.EmployeeViewAll();
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "department";
comboBox1.ValueMember = "empName";
}

SQL Server connection in WPF

I have a data base in SQL Server 2008 and connecting it in WPF application.I want to read data from table and show in datagrid. Connection is successfully created but when I show it in grid,it show db error(Exception handling).
This is what I am doing.Thanks in advance.
try
{
SqlConnection thisConnection = new SqlConnection(#"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(Get_Data);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
MessageBox.Show("connected");
//dataGrid1.ItemsSource = dt.DefaultView;
}
catch
{
MessageBox.Show("db error");
}
It shows connected when i comment the line sda.Fill(dt);
Your SqlCommand doesn't know you opened the connection- it requires an instance of SqlConnection.
try
{
SqlConnection thisConnection = new SqlConnection(#"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = Get_Data;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
dataGrid1.ItemsSource = dt.DefaultView;
}
catch
{
MessageBox.Show("db error");
}
You don't assign the command any connection. You open the connection then create a command, but don't link the two.
Try something like:
SqlConnection conn = new SqlConnection(#"Server(local);Database=Sample_db;Trusted_Connection=Yes;");
conn.Open();
string sql= "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(sql);
cmd.Connection = conn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
Assign Connection Object to SqlCommand Object.
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandTimeout = 15;
command.CommandType = CommandType.Text;
command.CommandText = queryString;
connection.Open();
//Perfom desired Action
}
Add thisConnection as 2nd parameter in
Sqlcommand cmd = new SqlCommand(Get_Data, thisConnection)
try {
string connectionstring = "#"
Server = (local) Database = Sample_dbTrusted_Connection = Yes;
"";
SqlConnection thisConnection = new SqlConnection(connectionstring);
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(Get_Data, thisConnection);
SqlDataAdapter sda = new SqlDataAdapter(cmd);`
DataTable dt = new DataTable("emp");
sda.Fill(dt);
MessageBox.Show("connected");
//dataGrid1.ItemsSource = dt.DefaultView;
} catch {
MessageBox.Show("db error");
}
I use this code with Oracle and hope it will help you.
First add reference Oracle.DataAccess then add namespace using Oracle.DataAccess.Client;
And using the following code
try
{
string MyConString = "Data Source=localhost;User Id= yourusername;Password=yourpassword;";
using (OracleConnection connection = new OracleConnection(MyConString))
{
connection.Open();
sqldb1 = "select * from DEMO_CUSTOMERS;";
using (OracleCommand cmdSe1 = new OracleCommand(sqldb1, connection))
{
DataTable dt = new DataTable();
OracleDataAdapter da = new OracleDataAdapter(cmdSe1);
da.Fill(dt);
db1.ItemsSource = dt.DefaultView;
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
XAML code:
<DockPanel>
<DataGrid Margin="10.0" DockPanel.Dock="Left" Name="db1" AutoGenerateColumns="True" >
</DataGrid>
</DockPanel>
public DataTable Execute(string cmd)
{
bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (networkUp)
{
try
{
SqlConnection connection = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand(cmd);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
DataTable dt = new DataTable();
sda.SelectCommand = command;
command.Connection = connection;
connection.Open();
sda.Fill(dt);
connection.Close();
if (dt != null && dt.Columns.Count > 0)
return dt;
else
return null;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
else
{
Console.WriteLine("Network is disconnect");
return null;
}
return null;
}
or :
public void ExecuteNonQuery(string cmd)
{
bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (networkUp)
{
try
{
SqlConnection connection = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand(cmd);
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

Categories

Resources