save a text and a value into combobox from a database table - c#

I want to take the name and surname of users from the table "EMPLOYE" (SQL DB) and save them in the combobox.
I want to save the ID of each user in the combobox value.
so this is my code =>
public void fill_combobox_users()
{
// auto-complete
comboBox3.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox3.AutoCompleteSource = AutoCompleteSource.ListItems;
da = new SqlDataAdapter("select ID_EMP, concat(NOM_EMP,' ',PRENOM_EMP) as 'nom_prenom' from EMPLOYE", cn);
DataTable dt = new DataTable();
try
{
cn.Open();
da.Fill(dt);
comboBox3.DataSource = dt;
comboBox3.DisplayMember = "nom_prenom";
comboBox3.ValueMember = "ID_EMP";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
}
The full name displayed without problems but the value no !!
The problem is that the combobox3.ValueMember take the string "ID_EMP" not the value from the table EMPLOYE !
ANY SOLUTIONS PLEASE ?

Edit your sql query like this. Should work
public void fill_combobox_users()
{
// auto-complete
comboBox3.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox3.AutoCompleteSource = AutoCompleteSource.ListItems;
da = new SqlDataAdapter("select ID_EMP,(NOM_EMP+ ' ' + PRENOM_EMP) AS NOMM from EMPLOYE", cn);
DataTable dt = new DataTable();
try
{
cn.Open();
da.Fill(dt);
comboBox3.DataSource = dt;
comboBox3.DisplayMember = "NOMM";
comboBox3.ValueMember = "ID_EMP";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
}

To get the value try
MessageBox.Show(comboBox3.SelectedValue.ToString())

Column Name is problem you want use Column index see here.
public void fill_combobox_users()
{
// auto-complete
comboBox3.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox3.AutoCompleteSource = AutoCompleteSource.ListItems;
da = new SqlDataAdapter("select ID_EMP,(NOM_EMP+ ' ' + PRENOM_EMP) AS NOMM from EMPLOYE", cn);
DataTable dt = new DataTable();
try
{
cn.Open();
da.Fill(dt);
comboBox3.DataSource = dt;
comboBox3.DisplayMember = dt.Columns[1].ColumnName;
comboBox3.ValueMember = dt.Columns[0].ColumnName;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
}

Related

DataGridView Image Column is throwing an Argument Exception: Parameter not valid

I am trying to load the data from MySQL database where the images are also placed in my table but when the form loads it gives the exception:
Any help would be appreciated
private void DealSuggestion_Load(object sender, EventArgs e)
{
try
{
status.Items.Add("active");
status.Items.Add("inactive");
id.Visible = false;
label7.Text = "";
conn.Open();
MySqlCommand cm = new MySqlCommand();
string query = "SELECT * from dealSuggestion where Status='inactive' LIMIT 8";
cm.CommandText = query;
cm.Connection = conn;
MySqlDataAdapter da = new MySqlDataAdapter(cm);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
DataGridViewImageColumn dgvimgcol = new DataGridViewImageColumn();
Check this out
https://www.c-sharpcorner.com/UploadFile/009464/insert-images-into-datagridview-in-windows-application-using/
Columns in datagridview are consider as string so you need to create an imagecolumn instead of binding it

Autocomplete textbox column in datagridview from SQL

I am trying to make a column which will suggest when I start typing in it and the data suggestions will be coming in a SQL table, I have tried using some codes here and in other sites but none seems to work properly to my needs.
Here is one of the codes that I have tried:
DataGridViewTextBoxColumn txt = new DataGridViewTextBoxColumn();
txt.Name = "Product Code";
txt.Width = 250;
dataGridView1.Columns.Add(txt);
con.Open();
try
{
cd = new SqlCommand();
cd.Connection = con;
cd.CommandText = "SELECT * FROM tblmaster";
da = new SqlDataAdapter();
da.SelectCommand = cd;
dt = new DataTable();
in the data source.
da.Fill(dt);
foreach (DataRow r in dt.Rows)
{
if (e.Control is TextBox)
{
DataGridViewTextBoxEditingControl txt = e.Control as DataGridViewTextBoxEditingControl;
txt.AutoCompleteCustomSource.Add(r.Field<string>("Product Code"));
txt.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
da.Dispose();
con.Close();

Object reference not set to instance of an object in crystalreportviewer in asp.net c#

I am trying to display some records to crystal report using Ado.Net dataset. When I am running my code it's showing this error. I debug my code but didn't get any exception.
Page Load
DataSet ds = new DataSet();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
ReportDocument rptDoc = new ReportDocument();
try
{
ds = new EmployeeDetails();
string EmpCode = GetValues("EmpCode");
ds = EmployeeCard(EmpCode);
string ReportName = "EmployeeCard.rpt";
ds.Tables[0].Merge(ds.Tables[0]);
rptDoc.Load(Server.MapPath(ReportName));
rptDoc.SetDataSource(ds.Tables[0]);
CrystalReportViewer1.ReportSource = rptDoc;
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally
{
rptDoc.Close();
rptDoc.Dispose();
}
}
and Rest of the Code
private DataSet EmployeeCard(string EmpCode)
{
SqlCommand cmd = new SqlCommand();
DataSet ds = null;
try
{
SqlDataAdapter adp;
string cn = Session["UserName"].ToString();
if (Connections.Connection[Session["UserName"].ToString()].State == ConnectionState.Closed)
Connections.Connection[Session["UserName"].ToString()].Open();
cmd.Connection = Connections.Connection[Session["UserName"].ToString()];
cmd.CommandText = "EmployeeMaster_pro";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("Option", "EmployeeCard".Trim());
cmd.Parameters.AddWithValue("EmpCode", EmpCode);
ds = new DataSet();
adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
dt = ds.Tables[0];
string value = dt.Rows[0][1].ToString();
return ds;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return ds;
}
finally
{
cmd.Parameters.Clear();
cmd.Dispose();
Connections.Connection[Session["UserName"].ToString()].Close();
}
}
public string GetValues(string Val)
{
string path = HttpContext.Current.Request.Url.AbsoluteUri;
string mainpath = path.Substring(path.IndexOf("?") + 1);
string[] Values = mainpath.Split('&');
for (int i = 0; i < Values.Length; i++)
{
string[] Data = Values[i].Split('=');
if (Data[0].ToString() == Val)
return Data[1].ToString();
}
return "";
}
When I debug my code. I didn't get any error. Everything is working fine but CrystalReportViewer is showing this Error. I don't understand where I am doing wrong here.
Please help guys....

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 combine fields in datagridview from Sql field names in c#

I have a DatagridView control that has 4 columns.
I want the FirstName, MiddleName and LastName to be merged and call it as FullName.
Like this :
My codes as of now is :
public void Data()
{
_da = new SqlDataAdapter();
_da.SelectCommand = cmd;
DataTable _dt = new DataTable();
_da.Fill(_dt);
BindingSource bs = new BindingSource();
bs.DataSource = _dt;
PresDG.DataSource = bs;
_da.Update(_dt);
}
private void President()
{
sc.Open();
cmd = new SqlCommand("SELECT * FROM TableVote WHERE Position='President'", sc);
try
{
Data();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sc.Close();
}
}
How do I do it in my Sql Statement? Thanks in advance :)
try using
cmd = new SqlCommand("SELECT FirstName+' '+MiddleName+' '+LastName as FullName,VCount FROM TableVote WHERE Position='President'", sc);

Categories

Resources