Hide empty row in combobox with C# - c#

I load data into combobox named cbxTravail. I have these lines that work fine but my problem is that I have some blank lines that I want to hide them or delete them from the list in combobox.
string myconnstrng = ConfigurationManager.ConnectionStrings["connstrng"].ConnectionString;
SqlConnection conn = new SqlConnection(myconnstrng);
DataSet ds = new DataSet();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("select TeethWorkID,Travail from TeethWorkNamesTable group by TeethWorkID, Travail", conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
// ds.Tables.Clear();
// adapter.Fill(ds);
cbxTravail.DisplayMember = "Travail";
cbxTravail.ValueMember = "TeethWorkID";
cbxTravail.DataSource = ds.Tables[0];
for (int i = cbxTravail.Items.Count - 1; i >= 0; i += -1)
{
if (cbxTravail.GetItemText(cbxTravail.Items[i]) == string.Empty)
{
cbxTravail.Items.RemoveAt(i);
}
}
}
catch (Exception ex)
{
//Exception Message
}
finally
{
conn.Close();
conn.Dispose();
}
I add this line for delete blank items from list but it doesn't work.
for (int i = cbxTravail.Items.Count - 1; i >= 0; i += -1)
{
if (cbxTravail.GetItemText(cbxTravail.Items[i]) == string.Empty)
{
cbxTravail.Items.RemoveAt(i);
}
}

Try to use like below:
if (String.IsNullOrWhiteSpace(cbxTravail.GetItemText(cbxTravail.Items[i]).Trim()))
{
cbxTravail.Items.RemoveAt(i);
}

Related

save a text and a value into combobox from a database table

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

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

Autocomplete Textbox does not show same name entries in c#

private void Autocomplete() // for customer name
{
try
{
con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT CustomerName FROM Customer where flag='y' ", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
List<string> list = new List<string>();
da.Fill(ds, "Customer");
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
int j = 0;
for (j = 0; j <= ds.Tables[0].Rows.Count - 1; j++)
{
col.Add(ds.Tables[0].Rows[j]["CustomerName"].ToString());
}
txtCustomerName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtCustomerName.AutoCompleteCustomSource = col;
txtCustomerName.AutoCompleteMode = AutoCompleteMode.Suggest;
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Example:
I have following entries in dataset
Roy
Rony
Roy
and If I type R in txtCustomerName then it shows Roy and Rony only. It is not showing Roy twice.
Try including last names so auto complete knows that roy 1 is different than roy 3

Combo box not getting filled

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

Categories

Resources