How do i bind data source to a ComboBox? - c#

So i currently have two combo boxes. One Being Manufacture the other being model. My sql query looks like this "Select Distinct Model From sheet1 where (Manufacture =#Manufacture)" this works when i execute it and if i were to fill a datagridtable. But if i try to place this into a combobox i get System.data.d...... etc for my selections. How can i just have it show the values instead of all this. What am i doing wrong?
private void ManuComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string manu = comboBox3.Text;
string conStr = "Data Source=CA-INVDEV\\RISEDB01;Initial Catalog=RISEDB01; Integrated Security=True";
string sqlcmd = "SELECT DISTINCT Model FROM Sheet1 WHERE (Manufacture =#Manufacture)";
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand(sqlcmd, conn);
cmd.Parameters.AddWithValue("#Manufacture", manu);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Close();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource3.DataSource = table;
ModelComboBox.DataSource = bindingSource3;
}
}
}

Can you give this a try?
using (SqlConnection conn = new SqlConnection(conStr))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlcmd, conn);
cmd.Parameters.AddWithValue("#Manufacture", manu);
SqlDataReader dr = cmd.ExecuteReader();
IList<string> modelList = new List<string>()
while (dr.Read())
{
modelList.add(dr[0].ToString());
}
ModelComboBox.DataSource = modelList;
}

If you have set the display member like:
ModelComboBox.DataSource = bindingSource3;
ModelComboBox.DisplayMember = "ColumnName";
And it still shows funny values, what are the values that it shows exactly?
Note, in a toolstrip it looks like you may have to also do:
ModelComboBox.BindingContext = this.BindingContext;
here is a reference

Try adding
ComboBox1.ItemsSource = bindingSource3
if this is your answer then mark it as answer

Related

c# display Access Database in DataGridView

First of all, here is my code:
private void Form5_Load(object sender, EventArgs e)
{
string strProvider = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:\Users\name\Documents\myprogramms\example.accdb";
string strSql = "Select * from score";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable scores = new DataTable();
da.Fill(scores);
data_example.DataSource = scores;
}
My goal is to display the data out of a MS Access Database. My codes has no error messages, but everytime I try to open the Data Grid View its completely empty.
your code snippet looks good. I cannot see any obvious issue.
Try to put breakpoint at the end of your method and check if datatable contains rows and rows contains any values in ItemArray.
Make sure your data_example DataGridView control is set AutoGenerateColumns = true (default) and check you have no other data source defined for your data_example DataGridView control. This code works for me.
private void Form1_Load(object sender, EventArgs e)
{
data_example.AutoGenerateColumns = true;
string strProvider = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:\aaa\CinemaBooking.accdb";
string strSql = "Select * from Booking";
using (OleDbConnection con = new OleDbConnection(strProvider))
{
using (OleDbCommand cmd = new OleDbCommand(strSql, con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
con.Open();
var scores = new DataTable();
da.Fill(scores);
data_example.DataSource = scores.DefaultView;
con.Close();
}
}
}
}
Maybe you can try to fill dataset with adapter and then use named table as datasource:
var dtSet = new DataSet();
da.Fill(dtSet, "Booking");
data_example.DataSource = dtSet.Tables["Booking"].DefaultView;

Does Not Contain Definition for DataBind

using (SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-IIDC3HF\SQLEXPRESS;Initial Catalog=EmployeeNotifier;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select Name,Salary FROM YOUR TABLE", con);
SqlDataReader dr = cmd.ExecuteReader();
dataGridView1.DataSource = dr;
dataGridView1.DataBind(); // causing problem here
con.Close();
}
I tried this code but this displays an error
Does Not Contain Definition for DataBind
var select =q;
var c = new SqlConnection(#"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];
Now i try this Code and its works really fine for me
Problem is that the datareader must iterate over the an object
try this instead create a custome class to hold your data.like below.
If that is too much trouble use an data adaptor and use DataSets
List<myCustomerCLass> list = new List<myCustomerCLass>();
con.Open();
SqlCommand cmd = new SqlCommand("Select Name,Salary FROM YOUR TABLE", con);
SqlDataReader dr = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
myCustomerCLass test = new myCustomerCLass();
test.property1 = reader["Property1"]
test.property2 = reader["Property2"]
test.property3 = reader["Property3"]
list.add(test);
}
}
reader.Close();
dataGridView1.DataSource = list;
dataGridView1.DataBind(); // causing problem here
con.Close();

Issue while deleting row using DataSet

Following code does not delete a row from dataset and dont update the database....
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
SqlDataAdapter adpt = new SqlDataAdapter("Select *from RegisterInfoB", con);
ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["FirstName"] == "praveen")
{
dr.Delete();
}
}
ds.Tables[0].AcceptChanges();
How to resolve this problem...How do I update my sql server database...by deleting a row from dataset..
I hope this will work for you:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
SqlDataAdapter adpt = new SqlDataAdapter("Select * from RegisterInfoB", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["FirstName"].ToString().Trim() == "praveen")
{
dr.Delete();
}
}
adpt.Update(ds);
Two Changes
1st: if (dr["FirstName"].ToString().Trim() == "praveen") trimming the blank spaces in your db's FirstName Field.
2nd : use adpt.Update(ds); to update your DB.
Another Way to doing it:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
string firstName= "praveen"; // this data will get from calling method
SqlDataAdapter adpt = new SqlDataAdapter("Select * from RegisterInfoB", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
string deleteQuery = string.Format("Delete from RegisterInfoB where FirstName = '{0}'", firstName);
SqlCommand cmd = new SqlCommand(deleteQuery, con);
adpt.DeleteCommand = cmd;
con.Open();
adpt.DeleteCommand.ExecuteNonQuery();
con.Close();
Similary, you can write query for UpdateCommand and InsertCommand to perform Update and Insert Respectively.
Find rows based on specific column value and delete:
DataRow[] foundRows;
foundRows = ds.Tables["RegisterTable"].Select("FirstName = 'praveen'");
foundRows.Delete();
EDIT: Adding a DeleteCommand to the data adapter (based on example from MSDN)
Note: Need an Id field here instead of FirstName, but I don't know your table structure for RegisterInfoB. Otherwise, we delete everyone named "praveen".
// Create the DeleteCommand.
command = new SqlCommand("DELETE FROM RegisterInfoB WHERE FirstName = #FirstName", con);
// Add the parameters for the DeleteCommand.
parameter = command.Parameters.Add("#FirstName", SqlDbType.NChar, 25, "FirstName");
parameter.SourceVersion = DataRowVersion.Original;
// Assign the DeleteCommand to the adapter
adpt.DeleteCommand = command;
To update a database with a dataset using a data adapter:
try
{
adpt.Update(ds.Tables["RegisterTable"]);
}
catch (Exception e)
{
// Error during Update, add code to locate error, reconcile
// and try to update again.
}
Sources: https://msdn.microsoft.com/en-us/library/xzb1zw3x(v=vs.120).aspx
https://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.120).aspx
hope that resolve the problem,
Try it:
var connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
var selectQuery = "Select * from RegisterInfoB";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand selectCommand = new SqlCommand(selectQuery, connection);
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
DataSet dataSet = new DataSet();
// you can use the builder to generate the DeleteCommand
adapter.DeleteCommand = builder.GetDeleteCommand();
// or
// adapter.DeleteCommand = new SqlCommand("DELETE FROM RegisterInfoB WHERE Id= #Id", connection);
adapter.Fill(dataSet, "RegisterInfoB");
// you can use the foreach loop
foreach (DataRow current in dataSet.Tables["RegisterInfoB"].Rows)
{
if (current["FirstName"].ToString().ToLower() == "praveen")
{
current.Delete();
}
}
// or the linq expression
// dataSet.Tables["RegisterInfoB"]
// .AsEnumerable()
// .Where(dr => dr["FirstName"].ToString().ToLower().Trim() == "praveen")
// .ToList()
// .ForEach((dr)=> dr.Delete());
var result = adapter.Update(dataSet.Tables["RegisterInfoB"]);
also you can add some events and put a breakpoint to see if the state is changing or if there is an error that prevent changes on the source:
dataSet.Tables["RegisterInfoB"].RowDeleted += (s, e) =>
{
var r = e.Row.RowState;
};
dataSet.Tables["RegisterInfoB"].RowDeleting += (s, e) =>
{
var r = e.Row.RowState;
};

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";
}

Use combobox value as query value (VC# 2k8 / ADO SQLITE)

I'm a newbie in VC# and ADO SQLITE...
I'm trying to change the content of a combobox according to the value present in another one...
My problem is here :
SQLiteCommand cmd3 = new SQLiteCommand("select distinct(ACTION) from ACTION_LIST where CATEGORY='comboBox1.text'", conn2);
What to use to do the job ? Here 'comboBox1.text' is see as a sentence not a variable...
Here is the code :
private void Form1_Load(object sender, EventArgs e)
{
using (SQLiteConnection conn1 = new SQLiteConnection(#"Data Source = Data\MRIS_DB_MASTER"))
{
conn1.Open();
SQLiteCommand cmd2 = new SQLiteCommand("select distinct(CATEGORY) from ACTION_LIST", conn1);
SQLiteDataAdapter adapter1 = new SQLiteDataAdapter(cmd2);
DataTable tbl1 = new DataTable();
adapter1.Fill(tbl1);
comboBox1.DataSource = tbl1;
comboBox1.DisplayMember = "CATEGORY";
adapter1.Dispose();
cmd2.Dispose();
}
using (SQLiteConnection conn2 = new SQLiteConnection(#"Data Source = Data\MRIS_DB_MASTER"))
{
conn2.Open();
SQLiteCommand cmd3 = new SQLiteCommand("select distinct(ACTION) from ACTION_LIST where CATEGORY='comboBox1.text'", conn2);
SQLiteDataAdapter adapter2 = new SQLiteDataAdapter(cmd3);
DataTable tbl2 = new DataTable();
adapter2.Fill(tbl2);
comboBox2.DataSource = tbl2;
comboBox2.DisplayMember = "ACTION";
adapter2.Dispose();
cmd3.Dispose();
}
}
Thanks
regards
Use System.Data.SQLite.SQLiteParameter. Try this out. (I may have some syntax wrong because I'm not able to test this right now...but it should be similar)
From your code:
SQLiteCommand cmd3 = new SQLiteCommand("select distinct(ACTION) from ACTION_LIST where CATEGORY=#category", conn2);
cmd3.Parameters.Add(new SQLiteParameter("#category",comboBox1.Text));
comboBox1.Text is the label of the combobox, you need comboBox1.SelectedValue. You also need to do what aaron says and add a parameter.

Categories

Resources