Okay so here's my code. Everything works and saves to the database.
Though, it only stores the current value that's displayed in the combobox.
I want it to store all 3 values, for each value has its own checkboxes.
How would I go about coding something that saves each of the 3 values and the corresponding checkboxes to the database(sql)?
Form
, Code
private void button1_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "insert into cloggingInfo(Date, PID, Operator, Type)values('"+labelTime.Text+"', '" + cboStatePid.Text + "', '" + cboStateOperator.Text + "', '" + cboStateType.Text + "')";
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
MessageBox.Show("Start added succesfully");
listView1.Items.Clear();
AddToListView();
}
}
Try to use "combobox.SelectedItem" or "combobox.SelectedValue". If your combobox is filled with datasource you need to define "DisplayMember" and "ValueMember" for it.
private void button1_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "insert into cloggingInfo(Date, PID, Operator, Type)values('"+labelTime.Text+"', '" + cboStatePid.SelectedItem+ "', '" + cboStateOperator.SelectedItem+ "', '" + cboStateType.SelectedItem+ "')";
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
MessageBox.Show("Start added succesfully");
listView1.Items.Clear();
AddToListView();
}
}
Try to get the combo box items for each combo box as shown below and then save it.
private void button1_Click(object sender, EventArgs e)
{
StringBuilder comboBox1Items = new StringBuilder();
foreach (var item in comboBox1.Items)
{
comboBox1Items.Append(item + " ");
}
string cb1Items = comboBox1Items.ToString();
}
Related
I am inserting data in the textbox1 and dropdown1 but the data is only saved in the query which is written at the second position"i.e in this case c_name". C_name is either empty or inserts null values.
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into market (m_name) values ('" + TextBox1.Text + "')";
cmd.CommandText = "insert into city (c_name) values('" + DropDownList1.SelectedValue + "')";
if (DropDownList1.SelectedValue == "-1")
{
Response.Write("Please select a city");
}
cmd.ExecuteNonQuery();
con.Close();
}
You should cmd.ExecuteNonQuery() after the first cmd.CommandText and then you have to do the same for your second cmd.CommandText, and both query will perform their actions.
protected void Button1_Click(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue == "-1")
{
Response.Write("Please select a city");
return; // Must return don't execute after 'if' part or use 'else' there
}
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into market (m_name) values ('" + TextBox1.Text + "')";
cmd.ExecuteNonQuery(); // First insert executed here
cmd.CommandText = "insert into city (c_name) values('" + DropDownList1.SelectedValue + "')";
cmd.ExecuteNonQuery(); // Second insert executed here
con.Close();
}
I am trying to insert and update data using same button. I have created method(uniqueEmail()) to check the email address exist in table or not. Using this method I am trying to insert data if email is not preset.
here is my code please correct me where I am going wrong.
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
public void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
if (uniqueEmail()==true)
{
cmd.CommandText = "update registeruser set email='" + TextBox1.Text + "', password='" + TextBox2.Text + "' where email='" + TextBox1.Text + "'";
}
else
{
cmd.CommandText = "insert into registeruser values('" + TextBox1.Text + "', '" + TextBox2.Text + "')";
}
cmd.ExecuteNonQuery();
con.Close();
}
public bool uniqueEmail()
{
string stremail;
string querye = "select count(email) as email from registeruser";
SqlCommand cmd = new SqlCommand(querye, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
try
{
stremail = dr["email"].ToString();
return(stremail != "0");
if (stremail != "0")
{
//errlblemail.Text = "email already exist";
return false;
}
}
catch (Exception e)
{
string message = "error";
message += e.Message;
}
finally
{
dr.Close();
}
}
return true;
}
}
You need to check for the count of the particular emailId, not the total count.
Modify the code as below:
public static bool uniqueEmail(string email)
{
string stremail;
string querye = "select count(email) as email from register where
email = '" + email + "'";
//Remaining Code
}
public static void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
if (uniqueEmail(TextBox1.Text)) == true)
//Remaining Code
}
#nirmala you should replace method
public void EmailCheck()
{
string constring = ConfigurationManager.ConnectionStrings["ConnData"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select * from EmailSignUp where EmailId= #EmailId", con);
cmd.Parameters.AddWithValue("#EmailId", this.txtEmail.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("EmailId = " + dr[5].ToString() + " Already exist");
txtEmail.Clear();
break;
}
}
}
Two Things need to be done
Pass the Email Id while calling
if (uniqueEmail()==true)
To
if (uniqueEmail(TextBox1.Text)==true)
And in uniqueEmail method chenage the query ()include where condition as below
public bool uniqueEmail(email)
{
string stremail;
string querye = "select count(email) as email from registeruser where email='" + email + "'";
//your remaining code
}
Hi Nirmala your code is correct only you need to put where clause to find the email id already exist in the Database.
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
public void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
if (uniqueEmail()==true)
{
cmd.CommandText = "update registeruser set email='" + TextBox1.Text + "', password='" + TextBox2.Text + "' where email='" + TextBox1.Text + "'";
}
else
{
cmd.CommandText = "insert into registeruser values('" + TextBox1.Text + "', '" + TextBox2.Text + "')";
}
cmd.ExecuteNonQuery();
con.Close();
}
public bool uniqueEmail()
{
string stremail;
string querye = "select count(email) as email from registeruser where email = '" +TextBox1.Text+ "'";
SqlCommand cmd = new SqlCommand(querye, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
try
{
stremail = dr["email"].ToString();
return(stremail != "0");
if (stremail != "0")
{
//errlblemail.Text = "email already exist";
return false;
}
}
catch (Exception e)
{
string message = "error";
message += e.Message;
}
finally
{
dr.Close();
}
}
return true;
}
}
I am a novice programmer (c #) and I stuck. I do not know why the compiler does not see the variable from another void. About a week ago in another program it worked and now does not want to. I was looking for a similar problem but I have not found.
public void Gridcommandevent(object sender, GridViewCommandEventArgs ev)
{
int index;
if (ev.CommandName == "Update")
{
index = Convert.ToInt32(ev.CommandArgument);
}
}
protected void GridView3_RowCommand(object sender, GridViewUpdateEventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["DGCodLocConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE Parts SET [LastModified] = '" + Permit + "' WHERE PartsID = '" + index + "'", con);
cmd.ExecuteNonQuery();
con.Close();
}
I want the index variable to the SqlCommand object.
By the way. Is this good code? It will be works ? i want to varible 'Permit' insert in to cell [LastModified] after updating data(row) in gridview.
It seems that this not works as it should :( I mean, variable 'index' is fine now, but code is just broken.
Declare your variable outside your void, so you can access it from all members. As you have it it is only visible to Gridcommandevent.
int index;
public void Gridcommandevent(object sender, GridViewCommandEventArgs ev)
{
if (ev.CommandName == "Update")
{
index = Convert.ToInt32(ev.CommandArgument);
}
}
protected void GridView3_RowCommand(object sender, GridViewUpdateEventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["DGCodLocConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE Parts SET [LastModified] = '" + Permit + "' WHERE PartsID = '" + index + "'", con);
cmd.ExecuteNonQuery();
con.Close();
}
As per Andreas Niedermair suggestion, and since you say you are a novice programmer, you should have a look at this MSDN Article.
I have 2 combo boxes and data grid view I can filter 2 combo boxes separately base on the table but I want to filter them based on 1st combo box. I tried different ways but my second combo box is empty.. nothing happens.. please help me with this.
{
String Query = " SELECT distinct [t_street_name] FROM [ICPS].[dbo].[tickets] ";
SqlConnection conDataBase = new SqlConnection(conString);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataAdapter sda = new SqlDataAdapter(cmdDataBase);
SqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string t_street_name = myReader["t_street_name"].ToString();
comboBox1.Items.Add(t_street_name);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void fillcombo1()
{
String Query = ("SELECT distinct [t_zone_name] FROM [ICPS].[dbo].[tickets] where [t_street_name] ='" + comboBox1.SelectedItem + "'conString ") ;
SqlConnection conDataBase = new SqlConnection(conString);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string t_zone_name = myReader["t_zone_name"].ToString();
comboBox2.Items.Add(t_zone_name);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection conDatabase = new SqlConnection(constring);
conDatabase.Open();
DataTable db = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(String.Format("select distinct * from" + " [ICPS].[dbo].[tickets] " +
"where [ICPS].[dbo].[tickets].[t_street_name] = '" + comboBox1.Text + "'" +
"and ([ICPS].[dbo].[tickets].[t_date_time_issued]) BETWEEN Convert(DATETIME, '{0}', 103) AND Convert(DATETIME, '{1}', 103)", StartDate.Value.ToString("dd/MM/yyyy"), EndDate.Value.ToString("dd/MM/yyyy")), constring);
sda.Fill(db);
dataGridView1.DataSource = db;
}
You're looking for filtering like state/city (as an example), correct? So if someone picks a state in the first combo box, then you want a list of cities within that state to populate in the second combo box. Correct?
Apart from the obvious comments about using parametrized queries and Using the SQL connection, have you actually checked the SQL statement directly in a database management program? To me it looks like there is no space in the statement text between
... comboBox1.Text + "'" +
"and ([ICPS].[dbo] ...
Apart from that you obviously need to load the second combo from the selected index event on the first combo.
I have tried it everything work fine now..
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conDatabase = new SqlConnection(constring);
comboBox2.SelectedIndex = -1;
comboBox2.Items.Clear();
if ( conDatabase.State == ConnectionState.Closed)
{
conDatabase.Open();
}
SqlCommand cmd = new SqlCommand(" select distinct sz_zone_name from [ICPS].[dbo].[spid_zones] " +
"inner join [ICPS].[dbo].[spid_street]" +
" on [ICPS].[dbo].[spid_street].ss_number = [ICPS].[dbo].[spid_zones].[sz_street_number]" +
" where [ICPS].[dbo].[spid_street].ss_name ='" + comboBox1.SelectedItem + "'", conDatabase);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
comboBox2.Items.Add(rd[0]);
}
Well, I have a simple program that is writing to a Database. I am trying to add validation to the textbox like this,
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
if (textBox1.Text.Length < -1)
{
MessageBox.Show("Don't Leave this field blank!");
}
}
catch
{
//todo
}
}
and My save to database code,
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
SqlCommand sql1 = new SqlCommand("INSERT into Book VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "')", con);
con.Open();
sql1.ExecuteNonQuery();
con.Close();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
But still it is adding blank data to the database and strange thing is in the database I have not allowed null but still data is getting added. Any clues where I am wrong?
I don't see you stopping the database to add empty content. You are validating on the textbox_textchanged event which will only validate the text when someone enters the data. You need to put the validation on button1's click event like this:
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(textBox1.Text.Trim()))
{
MessageBox.Show("Null String !!!!!!!!");
return;
}
SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
SqlCommand sql1 = new SqlCommand("INSERT into Book VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "')", con);
con.Open();
sql1.ExecuteNonQuery();
con.Close();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(textBox1.Text) || textBox1.Text.Trim().Length == 0)
{
//log
return;
}
SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
SqlCommand sql1 = new SqlCommand("INSERT into Book VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "')", con);
con.Open();
sql1.ExecuteNonQuery();
con.Close();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
An empty textbox.Text has zero byte length , not -1.
To be sure the textbox is not empty you should apply the Trim() to the current text
Also there is no need to catch an exception on this code.
Moreover, don't use the TextChanged event to validate the text box.
There is the Validating event for this purpose. (Remember to set CauseValidation=True for the control)
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Don't Leave this field blank!");
e.Cancel = true;
}
}
of course you could move all the validation in the code where do you update the database
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Don't Leave this field blank!");
return;
}
using(SqlConnection con = new SqlConnection(
"Server=DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
{
SqlCommand sql1 = new SqlCommand("INSERT into Book " +
"VALUES(#text1, #text2,#dtValue", con);
sql1.Parameters.AddWithValue("#text1", textBox1.Text);
sql1.Parameters.AddWithValue("#text2", textBox2.Text);
sql1.Parameters.AddWithValue("#dtValue", dateTimePicker1.Value.ToShortDateString());
con.Open();
sql1.ExecuteNonQuery();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
}