WPF - How to clear items before repopulating combobox - c#

I am trying to make cascading combo boxes. When I select values in combo boxes for the first time everything is OK, but when I return to first combo box and change to some other value, new items in the other combos are appended to the old items. This is my code bellow:
public Apartment()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection(Connection.cnnDatabase1);
Database1DataSet ds = new Database1DataSet();
private void FillLocation()
{
//locationCombo.Items.Clear()
SqlDataAdapter daLocation= new SqlDataAdapter("select * from Location", con);
daLocation.Fill(ds, "Location");
con.Open();
locationCombo.ItemsSource = ds.Tables["Location"].DefaultView;
locationCombo.DisplayMemberPath = "Location";
locationCombo.SelectedValuePath = "IdLocation";
con.Close();
}
private void FillCity(String IdLocation)
{
/*cityCombo.Items.Clear() -- I have tried inserting this,
but I am getting an error "Operation is not valid while ItemsSource is in use.
Access and modify elements with ItemsControl.ItemsSource instead." on that part
when I reselect the combo.*/
SqlDataAdapter daCity= new SqlDataAdapter("select * from City where IdLocation= " + IdLocation, con);
daCity.Fill(ds, "City");
con.Open();
cityCombo.ItemsSource = ds.Tables["City"].DefaultView;
cityCombo.DisplayMemberPath = "City";
cityCombo.SelectedValuePath = "IdCity";
con.Close();
}
private void FillStreet(String IdCity)
{
//cityCombo.Items.Clear()
SqlDataAdapter daStreet= new SqlDataAdapter("select * from Street where IdCity= " + IdCity, con);
daStreet.Fill(ds, "Street");
con.Open();
cityCombo.ItemsSource = ds.Tables["Street"].DefaultView;
cityCombo.DisplayMemberPath = "Street";
cityCombo.SelectedValuePath = "IdStreet";
con.Close();
}
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
FillLocation();
}
private void locationCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
String idLocation= locationCombo.SelectedValue.ToString();
FillCity(idLocation);
}
private void cityCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
String idCity = cityCombo.SelectedValue.ToString();
FillStreet(idCity);
}

Try this:
public Apartment()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection(Connection.cnnDatabase1);
Database1DataSet ds = new Database1DataSet();
private void FillLocation()
{
//locationCombo.Items.Clear()
SqlDataAdapter daLocation= new SqlDataAdapter("select * from Location", con);
ds.Tables["Location"].Clear();
daLocation.Fill(ds, "Location");
con.Open();
locationCombo.ItemsSource = ds.Tables["Location"].DefaultView;
locationCombo.DisplayMemberPath = "Location";
locationCombo.SelectedValuePath = "IdLocation";
con.Close();
}
private void FillCity(String IdLocation)
{
/*cityCombo.Items.Clear() -- I have tried inserting this,
but I am getting an error "Operation is not valid while ItemsSource is in use.
Access and modify elements with ItemsControl.ItemsSource instead." on that part
when I reselect the combo.*/
if(!String.IsNullOrWhiteSpace(IdLocation))
{
ds.Tables["City"].Clear();
SqlDataAdapter daCity= new SqlDataAdapter("select * from City where IdLocation= " + IdLocation, con);
daCity.Fill(ds, "City");
con.Open();
cityCombo.ItemsSource = ds.Tables["City"].DefaultView;
cityCombo.DisplayMemberPath = "City";
cityCombo.SelectedValuePath = "IdCity";
con.Close();
}
}
private void FillStreet(String IdCity)
{
if(!String.IsNullOrWhiteSpace(IdCity))
{
s.Tables["Street"].Clear();
SqlDataAdapter daStreet= new SqlDataAdapter("select * from Street where IdCity= " + IdCity, con);
daStreet.Fill(ds, "Street");
con.Open();
cityCombo.ItemsSource = ds.Tables["Street"].DefaultView;
cityCombo.DisplayMemberPath = "Street";
cityCombo.SelectedValuePath = "IdStreet";
con.Close();
}
}
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
FillLocation();
}
private void locationCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(locationCombo.SelectedValue != null)
{
String idLocation= locationCombo.SelectedValue.ToString();
FillCity(idLocation);
}
}
private void cityCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(cityCombo.SelectedValue != null)
{
String idCity = cityCombo.SelectedValue.ToString();
FillStreet(idCity);
}
}

Since cityCombo.Items.Clear() is not an option in this case as mentioned in the code comments, you can clear the datatable instead:
ds.Tables["City"].Clear();
And in order to avoid the NullReferenceException in cityCombo_SelectionChanged you can check the cityCombo.SelectedValue for null.

You are reusing the DataSet everywhere. So it will keep appending. As I said in the comments, either clear the DataSet or make a local one to each function.

Related

Why I can't change a single row?

When I sort the data according to the value named "TC NO" and make the edits, all the data in the table changes. For example; I have a, b, and c values. I'm trying to make the value "a" to "d" but the values a,b, and c each convert to the value "d". I just want the value I selected to change. Where am I doing wrong?
public partial class muster_guncelleme : Form
{
public muster_guncelleme()
{
InitializeComponent();
}
static string conString = "Server=localhost;Database=master; Trusted_Connection=True;";
SqlConnection baglanti = new SqlConnection(conString);
private void btn_arama_Click(object sender, EventArgs e)
{
baglanti.Open();
string kayit = "SELECT * from [user] where tc_no=#tc_no";
SqlCommand komut = new SqlCommand(kayit, baglanti);
komut.Parameters.AddWithValue("#tc_no", txt_tc.Text);
SqlDataAdapter da = new SqlDataAdapter(komut);
SqlDataReader dr = komut.ExecuteReader();
if (dr.Read())
{
lbl_tc.Text = dr["tc_no"].ToString();
txt_user.Text = dr["user_name"].ToString();
txt_pass.Text = dr["password"].ToString();
txt_name.Text = dr["full_name"].ToString();
bday_date.Text = dr["birth_date"].ToString();
txt_phone.Text = dr["phone_number"].ToString();
}
else
MessageBox.Show("Müşteri Bulunamadı.");
baglanti.Close();
}
private void muster_guncelleme_Load(object sender, EventArgs e)
{
}
private void btn_kaydet_Click(object sender, EventArgs e)
{
baglanti.Open();
string kayit = "update [user] set user_name=#user_name, password=#password, full_name=#full_name, phone_number=#phone_number";
SqlCommand komut = new SqlCommand(kayit, baglanti);
komut.Parameters.AddWithValue("#user_name", txt_user.Text);
komut.Parameters.AddWithValue("#password", txt_pass.Text);
komut.Parameters.AddWithValue("#full_name", txt_name.Text);
komut.Parameters.AddWithValue("#phone_number", txt_phone.Text);
komut.ExecuteNonQuery();
baglanti.Close();
MessageBox.Show("Kullanıcı Bilgileri Güncellendi.");
}
}

Read Datatable and do a loop in rows async c#

I'm trying to implement asynchronous methods in my program, and I want to read each row asynchronously from a datatable.
I have the following situation:
private void VerifyPermissions()
{
try
{
string constring = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", AcessoBancoDados.server, AcessoBancoDados.user, AcessoBancoDados.password, AcessoBancoDados.database);
MySqlConnection con = new MySqlConnection();
con.ConnectionString = constring;
con.Open();
var query = "SELECT id FROM users";
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataAdapter da = new MySqlDataAdapter(query, con);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
foreach (DataRow item in dt.Rows)
{
Messagebox.Show(item["id"].ToString());
}
}
And the call method:
private void button1_Click(object sender, EventArgs e)
{
VerifyPermissions()
}
Anyone can show me an async situation for this? Thanks.
according to your comment you would need something like my code below.
If you use SqlCommand instead of SqlDataAdapter you will have async methods already and don't need to create a task.
(also don't mix ui and data access. keep them separate.)
private async void button1_Click(object sender, EventArgs e)
{
await VerificarPermissoes();
}
private async Task VerificarPermissoes()
{
await Task.Run(() =>
{
// put your code from above here.
});
}
Well, you can do this basically by creating tasks in c#, see the example below
private void VerificarPermissoes()
{
try
{
DataTable dt = new DataTable();
string constring = String.Format("");
string query = "SELECT id FROM users";
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
DbCommand command = con.CreateCommand();
command.CommandText = query;
dt.Load(command.ExecuteReader());
}
foreach (DataRow item in dt.Rows)
{
Task.Factory.StartNew(delegate () { ProcessItem(item["id"].ToString()); });
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ProcessItem(string item)
{
AddControl(myControl, childControl);
}
private void button1_Click(object sender, EventArgs e)
{
VerificarPermissoes();
}
private void AddControl(Control ctrl, Control child)
{
if (ctrl.InvokeRequired)
{
Action act = delegate () { AddControl(ctrl, child); };
this.Invoke(act);
}
else
{
ctrl.Controls.Add(child);
}
}

Update SQL query, unsure why it isn't working as no errors are appearing

I have been staring at this UPDATE statement for a long while and are unsure why my table isn't changing. When I press the button no error appears but my table doesn't not get updated either, I have checked that all of my variables have values on debug and they do.
I'd appreciate any help anyone can give me!
This is the code that contains the statement I need help with:
private void button1_Click(object sender, EventArgs e)
{
string studentanswertext = textBox1.Text;
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
string y = GlobalVariableClass.Signedinteacher;
Convert.ToInt32(y);
MessageBox.Show(y);
MessageBox.Show(Convert.ToString(CurrentQuestionID));
MessageBox.Show(studentanswertext);
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command20 = new SqlCommand(#"UPDATE QuestionStudentAssociation SET ([StudentAnswer]=#StudentAnswertext) WHERE ([QuestionID]=#CurrentQID AND [StudentID]=#SignedinStudent )", connect);
command20.Parameters.AddWithValue("#StudentAnswertext", studentanswertext);
command20.Parameters.AddWithValue("#CurrentQID", CurrentQuestionID);
command20.Parameters.AddWithValue("#SignedinStudent", y);
command20.BeginExecuteNonQuery();
connect.Close();
}
This is the whole code for my form if anyone wanted to look at it just in case that is affecting the button even handler:
namespace ComputingA2_Official_Project
{
public partial class CurrentlySetTestForm : Form
{
Timer loopTimer = new Timer();
private int CurrentQuestionID { get; set; }
private string QuestionSpace { get; set; }
public CurrentlySetTestForm()
{
InitializeComponent();
}
private void CurrentlySetTestForm_Load(object sender, EventArgs e)
{
string y = GlobalVariableClass.Signedinteacher;
Convert.ToInt32(y);
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command18 = new SqlCommand("SELECT MIN([QuestionID]) AS QuestionID FROM QuestionStudentAssociation WHERE ( [StudentID]=#Signedinstudent AND [StudentAnswer] IS NULL )", connect);
command18.Parameters.AddWithValue("#Signedinstudent", y);
var reader = command18.ExecuteReader();
while (reader.Read())
{
CurrentQuestionID = Convert.ToInt32(reader[0]);
SqlCommand command19 = new SqlCommand("SELECT ([Question Space]) FROM Questions WHERE ([QuestionID]=#CurrentQID)", connect);
command19.Parameters.AddWithValue("#CurrentQID", CurrentQuestionID);
using (SqlDataReader reader2 = command19.ExecuteReader())
{
while (reader2.Read())
{
QuestionSpace = Convert.ToString(reader2[0]);
label1.Text = QuestionSpace;
}
}
}
connect.Close();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string studentanswertext = textBox1.Text;
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
string y = GlobalVariableClass.Signedinteacher;
Convert.ToInt32(y);
MessageBox.Show(y);
MessageBox.Show(Convert.ToString(CurrentQuestionID));
MessageBox.Show(studentanswertext);
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command20 = new SqlCommand(#"UPDATE QuestionStudentAssociation SET ([StudentAnswer]=#StudentAnswertext) WHERE ([QuestionID]=#CurrentQID AND [StudentID]=#SignedinStudent )", connect);
command20.Parameters.AddWithValue("#StudentAnswertext", studentanswertext);
command20.Parameters.AddWithValue("#CurrentQID", CurrentQuestionID);
command20.Parameters.AddWithValue("#SignedinStudent", y);
command20.BeginExecuteNonQuery();
connect.Close();
}
private void timer1_Tick(object sender, EventArgs e)
{
}
}
}
I believe the issue is that you are executing the command asynchronously (BeginExecuteNonQuery), but never calling EndExecuteNonQuery to commit it. I also suspect you could just call it synchronously like this:
command20.ExecuteNonQuery();

Filtering combobox with another combobox value

I have three combo-box which filtering value in different tables. For the first two combo-box i have no problem but for the third combo-box, I got error show input strings was not in correct format. I using the same code for the other two and it working correctly. Can someone specify how to troubleshoot this problem?
Here my code:-
This one is for combobox two which worked perfectly:-
private void cbBridge_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbBridge.SelectedValue.ToString() != null)
{
int BridgeID = Convert.ToInt32(cbBridge.SelectedValue.ToString());
FillPier(BridgeID);
}
}
This is the code which show error
private void cbPier_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbPier.SelectedValue.ToString() != null)
{
int PierID = Convert.ToInt32(cbPier.SelectedValue.ToString());
FillDataPoint(PierID);
}
}
I hope someone can show me how to rectify this problem. Thanks.
***UPDATE****
Here the full code
private void FillPier(int BridgeID)
{
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT PierID, PierName, BridgeID FROM tbPier WHERE BridgeID = #BridgeID";
cmd.Parameters.AddWithValue("#BridgeID", BridgeID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
cbPier.DataSource = objDs.Tables[0];
cbPier.DisplayMember = "PierName";
cbPier.ValueMember = "PierID";
}
}
private void FillDataPoint(int PierDP)
{
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT PierID, InspectDate FROM tbDatapoint WHERE PierID = #PierID";
cmd.Parameters.AddWithValue("#PierID", PierDP);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
cbInspect.DataSource = objDs.Tables[0];
cbInspect.DisplayMember = "InspectDate";
cbInspect.ValueMember = "PierID";
}
}
private void ViewBridge_Load(object sender, EventArgs e)
{
FillBridge();
}
private void cbBridge_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbBridge.SelectedValue.ToString() != null)
{
int BridgeID = Convert.ToInt32(cbBridge.SelectedValue.ToString());
FillPier(BridgeID);
}
}
private void cbPier_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbPier.SelectedIndex != 1)
{
int PierDP = Convert.ToInt32(cbPier.SelectedValue.ToString());
FillDataPoint(PierDP);
}
}
Check if this can be converted to int first like this:
int x = 0
private void cbPier_SelectedIndexChanged(object sender, EventArgs e)
{
if (Int32.TryParse(cbPier.SelectedValue.ToString(), out x))
{
int PierID = Convert.ToInt32(cbPier.SelectedValue.ToString());
FillDataPoint(PierID);
}
}
Or using the SelectedIndex property:
if(cbPier.SelectedIndex != -1)
{
.....
}
What are the cbPier.DisplayMember and cbPier.ValueMember ? Is the diplay member the string and value member the int? Double check if that's the case first ...

Populating TextBox, The data type is not valid for the boolean operation

I got a ComboBox with a table as data source, ID as a value member and a name as a display member.
Selecting a name from the ComboBox should populate 6 TextBoxes with data.
Exception:
The data type is not valid for the boolean operation. [ Data type (if known) = int,Data type (if known) = nvarchar ]
Code:
void FillComboBox()
{
//Fill Combo Box
SqlCeDataAdapter da = new SqlCeDataAdapter(" SELECT CustomerID, Name FROM Customers", clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
cBox1.DataSource = ds.Tables[0];
cBox1.ValueMember = "CustomerID";
cBox1.DisplayMember = "Name";
}
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
clsMain.con.ConnectionString = #"Data Source=|DataDirectory|\Database\Sales.sdf";
clsMain.con.Open();
FillComboBox();
}
private void btnSave_Click(object sender, EventArgs e)
{
//Save Button
SqlCeCommand cmd = new SqlCeCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = " INSERT INTO Customers (Name, Phone1, Phone2, Address, Notes) VALUES (#Name, #Phone1, #Phone2, #Address, #Notes) ";
cmd.Connection = clsMain.con;
cmd.Parameters.AddWithValue("#Name", txt2.Text.Trim());
if (txt3.Text != "")
{
cmd.Parameters.AddWithValue("#Phone1", Convert.ToInt32(txt3.Text));
}
else
{
cmd.Parameters.AddWithValue("#Phone1", Convert.DBNull);
}
if (txt4.Text != "")
{
cmd.Parameters.AddWithValue("#Phone2", Convert.ToInt32(txt4.Text));
}
else
{
cmd.Parameters.AddWithValue("#Phone2", Convert.DBNull);
}
cmd.Parameters.AddWithValue("#Address", txt5.Text.Trim());
cmd.Parameters.AddWithValue("#Notes", txt6.Text.Trim());
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");
}
private void cBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (cBox1.SelectedIndex >= 0)
{
String Code = "SELECT * FROM Customers WHERE CustomerID=" + cBox1.SelectedValue.ToString();
SqlCeDataAdapter da = new SqlCeDataAdapter(Code, clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
txt1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
txt2.Text = ds.Tables[0].Rows[0]["Name"].ToString();
txt3.Text = ds.Tables[0].Rows[0]["Phone1"].ToString();
txt4.Text = ds.Tables[0].Rows[0]["Phone2"].ToString();
txt5.Text = ds.Tables[0].Rows[0]["Address"].ToString();
txt6.Text = ds.Tables[0].Rows[0]["Notes"].ToString();
}
}
Table Details:
To follow up on my comment (with the caveat that I have never worked with SQL CE, but I'm pretty sure (99.9%) that this is correct).
In you SQL query string, you surround the customer id with single quotes ('). You use single quotes in SQL ("nomral" SQL at least) for character (char\varchar etc) and date values. You pass numeric values without single quotes.
You didn't indicate what line was giving you the exception, but based on the table structure and what you are doing (you gave good detail in your question, by the way), it seems that the error message is telling you that you're trying to compare an int to a varchar, and that's not allowed (because they are different data types, as the error indicates).
To resolve this, simply remove the single quotes from the value in your WHERE clause and construct your query as follows:
String Code = "SELECT * FROM Customers WHERE CustomerID=" + cBox1.SelectedValue;
Thank you, Its working for me.
I am having some customers name in comboBox2. Based on the selected name textbox will return CustomerID and Date of Allocation values.
Following are the code for that:
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if(comboBox2.SelectedIndex>0)
{
con = new SqlCeConnection(s);
con.Open();
string code = "select CustomerID,Date_of_Allocation from lockerdetails
where CustomerName='" + comboBox2.SelectedValue.ToString() + "'";
SqlCeDataAdapter da = new SqlCeDataAdapter(code, con);
SqlCeCommandBuilder cmd = new SqlCeCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds);
textBox1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
textBox5.Text = ds.Tables[0].Rows[0]["Date_of_Allocation"].ToString();
}
}
catch(SystemException se)
{
MessageBox.Show(se.Message);
}

Categories