Combo box not getting filled - c#

I have this function which I am using to fill my combobox but its not getting filled. I am not getting any error either.
public List<string> showStudents()
{
List<string> list = new List<string>();
string rollno;
command = connection.CreateCommand(); //command and connection have been initialized earlier..
command.CommandText = "select RollNo from student";
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
rollno = reader["RollNo"].ToString();
list.Add(rollno);
}
reader.Close();
return list;
}
catch (Exception)
{
throw;
}
finally
{
connection.Close();
}
}
}
}
comboBox.DataSource=showStudents();
What may be the problem? Please help!!
Thank You..
Have got the answer.. :)
foreach(string str in showStudent())
{
comboBox.Items.Add(str);
}

If the reader returns results you should set the members "DisplayMember" and "ValueMember" of the ComboBox to tell which column the combox should use for the text displayed and the value of the item.
Like this :
comboBox.DisplayMember = "RollNo"
comboBox.ValueMember= "RollNo"
You can put it right after setting the DataSource. Tell us if it helps.

See this sample example and try with ur code
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"));
}

Related

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();

How to compare DataTable row with listbox items

I wanna compare list items in a listbox with with a DataTable column rows named "time" when I select a date in the monthcalendar, Im trying to remove the items in the listbox if they are equal to the values in the column, if not then use the default items I have in the begining. But Iam getting the message: item colection cannot be modified when Datasource property is set. Please help me correct the code:
private void monthCAL_DateChanged(object sender, DateRangeEventArgs e)
{
string date = monthCAL.SelectionStart.Date.ToString("yyyyMMdd");
string connetionString = null;
MySqlConnection connection;
MySqlCommand command;
MySqlDataAdapter adapter = new MySqlDataAdapter();
DataSet ds = new DataSet();
string sql = null;
connetionString = "datasource=localhost; database=bokning;port=3306;username=root;password=666666";
sql = "select day, time from system where day='" + date + "'";
connection = new MySqlConnection(connetionString);
try
{
connection.Open();
command = new MySqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
connection.Close();
MyDateT = ds.Tables[0];
if (MyDateT.Rows.Count > 0)
{
foreach (DataRow dr in MyDateT.Rows) {
for (int i = 0; i < MydefaultList.Length; i++)
{
if (MydefaultList[i].ToString().Equals(dr["time"].ToString())) {
listB1.Items.Remove(MydefaultList[i]);
//listB1.DataSource = MydefaultList;
}
}
}
}
else
{
listB1.DataSource = MydefaultList;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
From my understanding you are not able to remove items from a Listbox that have a DataSource property.
This link can describe more in depth:
http://www.codeproject.com/Questions/758161/Items-collection-cannot-be-modified-when-the-DataS
You will need to set the DataSource to null, make the changes you want to make and then re-add the DataSource.
You have to create a new list to store the limited options. Please see the edited code below.
private void monthCAL_DateChanged(object sender, DateRangeEventArgs e)
{
string date = monthCAL.SelectionStart.Date.ToString("yyyyMMdd");
string connetionString = null;
MySqlConnection connection;
MySqlCommand command;
MySqlDataAdapter adapter = new MySqlDataAdapter();
DataSet ds = new DataSet();
string sql = null;
connetionString = "datasource=localhost; database=bokning;port=3306;username=root;password=666666";
sql = "select day, time from system where day='" + date + "'";
connection = new MySqlConnection(connetionString);
try
{
connection.Open();
command = new MySqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
connection.Close();
MyDateT = ds.Tables[0];
List<string> limitedList = MyDefaultList; //added line
if (MyDateT.Rows.Count > 0)
{
foreach (DataRow dr in MyDateT.Rows) {
for (int i = 0; i < MydefaultList.Length; i++)
{
if (MydefaultList[i].ToString().Equals(dr["time"].ToString())) {
limitList.Remove(MyDefaultList[i]);
listB1.DataSource = limitedList;
//listB1.Items.Remove(MydefaultList[i]); offending line
//listB1.DataSource = MydefaultList; offending line
}
}
}
}
else
{
listB1.DataSource = MydefaultList;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

How to check weather my comboobx value is already inserted and if its inserted already in database the perticular value wont be visible in the list

I have a strange problem,
I'm working with win-form which is coding in c#..and sql server
In a form I have a Combo-box which is collected data by the database(say 1).
and later I have to Insert that particular value/member details into another database(say 2)
Here My problem raises,,Once My combo-box any value is inserted into 2nd database,that particular value/member should not visible in the combo-box for the next time on the same day..
Of course Here I'm using datetimepicker..
Here I'm using following code...and Of-course it is wrong..Please Help me
SqlCommand cmd1 = new SqlCommand("select employee_id,Empployee_Name,date from dailyattendance", cn);
SqlDataReader sdr;
DataTable dt = new DataTable();
sdr = cmd1.ExecuteReader();
if (sdr.Read())
{
string employeeid = (string)sdr["employee_id"];
string employeename = (string)sdr["Empployee_Name"];
string date = (string)sdr["date"];
try
{
//cn.Open();
SqlCommand cmd = new SqlCommand("select employee_id,employee_name from Employee_Details", cn);
SqlDataReader sdr1;
DataTable dt1=new DataTable();
sdr1 = cmd.ExecuteReader();
dt1.Load(sdr1);
if (sdr1.Read())
{
string date1=dateTimePicker1.Value.ToString("dd/MM/yyyy");
if ()//here the main problem
{
string employeeid1 = (string)sdr1["employee_id"];
string employeename1 = (string)sdr1["employee_name"];
comboBox1.DisplayMember = employeeid1;
comboBox1.DisplayMember = employeename1;
comboBox1.DataSource=dt1;
cn.Close();
}
}
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
try
{
string dtp = dateTimePicker1.Value.ToString("dd/MM/yyyy");
string query = "select employee_id,employee_name,image_of_employee,image_path from Employee_Details where employee_id not in (select employee_id from dailyattendance where date = '" + dtp + "')";//Here added a new query which is working
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dtr);
foreach (DataRow row in dt.Rows)
{
var name = (string)row["employee_name"];
row["employee_name"] = name.Trim();
}
comboBox1.ValueMember = "employee_id";
comboBox1.DisplayMember = "employee_name";
listBox1.ValueMember = "employee_id";
listBox1.DisplayMember = "employee_name";
comboBox1.DataSource = dt;
listBox1.DataSource = dt;
comboBox1.SelectedItem = null;
listBox1.SelectedItem = null;
cn.Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
Simply at query added some workable logic

ComboBox cannot display new value added

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

How do i bind data source to a ComboBox?

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

Categories

Resources