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);
}
}
Related
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);
}
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....
//.aspx.cs code:
protected void ddldistrict_SelectedIndexChanged(object sender, EventArgs e)
{
try {
ddltaluka.Enabled = true;
string d1 = ddldistrict.Text;
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;User Id=postgres;Password=*******;Database=guj_data;");
conn.Open();
string sql = "SELECT tname FROM taluka_geo_bnd_box WHERE district='"+d1+"'";
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
ds.Reset();
da.Fill(ds);
dt = ds.Tables[0];
ddltaluka.DataSource = ds;
ddltaluka.DataTextField = "tname";
ddltaluka.DataBind();
conn.Close();
}
catch(Exception e3)
{
throw e3;
}
}
protected void ddltaluka_SelectedIndexChanged(object sender, EventArgs e)
{
try {
ddlvillage.Enabled = true;
string t1 = ddltaluka.Text;
string d1 = ddldistrict.Text;
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;User Id=postgres;Password=*****;Database=guj_data;");
conn.Open();
string sql = "SELECT vname FROM village_boundary_geo_bnd_box WHERE tname='"+t1+"' AND district='"+d1+"'";
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
ds.Reset();
da.Fill(ds);
dt = ds.Tables[0];
ddlvillage.DataSource = ds;
ddlvillage.DataTextField = "vname";
ddlvillage.DataBind();
conn.Close();
}
catch(Exception e4)
{
throw e4;
}
}
If I am understanding you correctly;
ddlvillage data bind happens at page load
when the method ddltaluka_selectedIndexChanged is called, you try to bind new data do it but it goes back to the original ddlVillage list?
If this is the case you need to only do the initial databind for ddlVillage on the initial page load and not each post back
if (!IsPostBack)
{
//bind your initial data here
}
I have 2 tables in MySql (privacy , lawsuit_under_500) ,
In privacy i have 2 columns (id , nameofcase ) ,
In lawsuit_under_500 4 columns(id,nameofcase,priceone,pricetwo) ,
I make a form with a datagridview and i want to execute this query :
select privacy.id,lawsuit_under_500.id,privacy.nameofcase, lawsuit_under_500.priceone, lawsuit_under_500.pricetwo
From privacy inner join lawsuit_under_500
where lawsuit_under_500.id=5 and privacy.id=1 || lawsuit_under_500.id=1 and privacy.id=2 || lawsuit_under_500.id=10 and privacy.id=3
ORDER BY privacy.id
In the form i have:
public Form55()
{
InitializeComponent();
}
private void Form55_Load(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
I have put the tables in my DataSet but I cant figure out how to make it. I tried to make privacyBindingSourse in the datagridview and i added manually 2 buttons for priceone and pricetwo put i cant put the query so i can get the information.
Any ideas/help how to make it ?
BEFORE YOU ANSWER IF YOU HAVE ANY QUESTION PLEASE ASK ME
using MySql.Data.MySqlClient;
MySqlConnection conn = new MySqlConnection("Your MY SQL connection");
MySqlCommand cmd = new MySqlCommand("Your Mysql query");
MySqlDataReader dr=cmd.ExecuteReader();
gridview1.datasource=dr;
gridview1.databind();
// try this also
connectionString = "Your Connection";
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
{
mySqlDataAdapter = new MySqlDataAdapter("Your Query", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
//close connection
this.CloseConnection();
}
I made it with this way
private void Form56_Load(object sender, EventArgs e)
{
try
{
MySqlConnection cnn = new MySqlConnection("MY CONNECTION");
cnn.Open();
// - DEBUG
// MessageBox.Show("Connection successful!");
MySqlDataAdapter MyDA = new MySqlDataAdapter();
MyDA.SelectCommand = new MySqlCommand("MY QUERY", cnn);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
Close();
}
}
static public SqlCeConnection OpenSQL()
{
SqlCeConnection cncount = new SqlCeConnection(#"Data Source = " + Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + #"\Database.sdf; Password =''");
return cncount;
}
static public DataTable DoSelect( string strSQL)
{
SqlCeConnection cn = OpenSQL();
DataTable dtRetValue = new DataTable();
using (SqlCeDataAdapter da = new SqlCeDataAdapter())
{
using (SqlCeCommand cmd = cn.CreateCommand())
{
cmd.CommandText = strSQL;
da.SelectCommand = cmd;
if (cn.State == ConnectionState.Closed)
{
cn.Open();
}
try
{
//using (SqlCeDataReader reader = da.SelectCommand.ExecuteReader())
SqlCeDataReader metsDr = da.SelectCommand.ExecuteReader();
dtRetValue.Load(metsDr);
return dtRetValue;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error - DoSelect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
return null;
}
}
}
}
Insert in Button
string sql1 = "YOURE QUERY ";
DataTable dt1 = SQLcode.DoSelect(sql1);
dgvcompany.DataSource = dt1;
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"));
}