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 ...
Related
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.");
}
}
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);
}
}
I have created a method with a string "test" that holds my SqlCommand query.
test = '201813'
public void temp()
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT LEFT(CONVERT(VARCHAR(10),GETDATE(),120),4)+ CAST((DATEPART(ISOWK,GETDATE()) - 2) AS NVARCHAR(2))", con);
con.Open();
string test = (string)cmd.ExecuteScalar();
con.Close();
}
}
The question now is How can I reuse this string in my following rowdatabound event?
protected void gwPlanning_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells.Count > 0)
{
//Translate header text
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[12].Text = test.ToString();
}
}
}
I'm trying to use e.Row.Cells[12].Text = **test.ToString();
Can anyone help me on what im doing wrong?
In your code, the string variable test is a local variable for the temp() and if you want to use that it in gwPlanning_RowDataBound, either you have to make the function temp to return a string value or you have to save the value in a global variable.
temp() to return a string value.
Code:
public string temp()
{
string test = string.Empty;
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT LEFT(CONVERT(VARCHAR(10),GETDATE(),120),4)
+ CAST((DATEPART(ISOWK,GETDATE()) - 2) AS NVARCHAR(2))", con);
con.Open();
test = (string)cmd.ExecuteScalar();
con.Close();
}
return test;
}
protected void gwPlanning_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells.Count > 0)
{
//Translate header text
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[12].Text = temp().ToString();
}
}
}
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.
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();