Overwrite previous checkbox value on button click - c#

I am saving a checkbox value using 'Yes' & 'No' and my problem is I have a button click that would allow the user to change the value.
So my logic is, if button is clicked the checkbox value that is no would change to yes.
Here is what I have to save the information originally:
public void StoredProcedure()
{
string privateItem = Private.Checked ? "Y" : "N";
connection.connection1();
if (connection.con.State == ConnectionState.Closed)
connection.con.Open();
using (SqlCommand cmd = new SqlCommand("SaveImage", connection.con))
{
cmd.Parameters.Add("#privatecheck", SqlDbType.Char).Value = privateItem;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
connection.con.Close();
}
Basically I have a stored procedure in my database that will save my information.
Now what I was thinking to update one value is to basically do the same thing but it resulted in an error for me.
Any help on how to overwrite a previously saved checkbox value would be extremely helpful!
Thanks

I am not entirely clear on what you are asking for so my answer gives two possible solutions:
If you are looking to modify whether or not the control itself is checked or not checked here is a piece of sample code from MSDN:
private void AdjustMyCheckBoxProperties()
{
// Change the ThreeState and CheckAlign properties on every other click.
if (!checkBox1.ThreeState)
{
checkBox1.ThreeState = true;
checkBox1.CheckAlign = ContentAlignment.MiddleRight;
}
else
{
checkBox1.ThreeState = false;
checkBox1.CheckAlign = ContentAlignment.MiddleLeft;
}
// Concatenate the property values together on three lines.
label1.Text = "ThreeState: " + checkBox1.ThreeState.ToString() + "\n" +
"Checked: " + checkBox1.Checked.ToString() + "\n" +
"CheckState: " + checkBox1.CheckState.ToString();
}
If instead you are looking to modify a column in a table, an UPDATE SQL statement will do that for here, MSDN has a nice walkthrough on how to use LINQ and SQL to achieve this which I would recommend reading.
However I see you are using SqlCommand so here is the example code on how to perform an update command (again) from MSDN:
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
All of the above pieces should help you generate a solution.

Related

Fill ComboBox on form in a method triggered by a button

First of all, if I click a button the method cbBefüllen will execute.
private void btnEntfernen_Click(object sender, EventArgs e)
{
FeiertageEntfernen entfernen = new FeiertageEntfernen();
entfernen.cbBefüllen();
entfernen.Show();
entfernen.Focus();
}
The following method is just here as an interface between my form and a class. (Please don't ask, in my code I have some good reasons for it ;) ).
public void cbBefüllen()
{
database.cbFeiertagebefüllen();
}
The method cbFeiertagebefüllen (tries to) fills my ComboBox, which is located in the form "feiertagentfernen".
public void cbFeiertagebefüllen()
{
FeiertageEntfernen feiertagentfernen = new FeiertageEntfernen();
string Query = #"select bezeichnung from feiertage";
using (var command = new SQLiteCommand(Query, sqlite_conn))
{
if (sqlite_conn.State != ConnectionState.Open)
{
sqlite_conn.Open();
}
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
string übergabe = reader.GetString(0);
feiertagentfernen.cbFeiertag.Items.Add(übergabe);
}
}
}
}
But after this whole process my ComboBox is still empty. The reader in the last picture picks the correct value from the database, but somehow it won't write it into the ComboBox.
Your problem is in this line:
FeiertageEntfernen feiertagentfernen = new FeiertageEntfernen();
in your cbFeiertagebefüllen()
You make a new form but you want your combo box from the form from the 1st piece of code to be filled. To fix this you could pass along an instance of the form to the filling method.
The updated 2 pieces of code will be (first piece can be left alone):
In cbBefullen:
database.cbFeiertagebefüllen(this);
//'this' means we're passing along the form as parameter
In cbFeiertagebefüllen:
public void cbFeiertagebefüllen(FeiertageEntfernen feiertagentfernen)
{
string Query = #"select bezeichnung from feiertage";
using (var command = new SQLiteCommand(Query, sqlite_conn))
{
if (sqlite_conn.State != ConnectionState.Open)
{
sqlite_conn.Open();
}
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
string übergabe = reader.GetString(0);
feiertagentfernen.cbFeiertag.Items.Add(übergabe);
}
}
}
}
The FeiertageEntfernen form instance on which you're filling the cbFeiertag combo box in cbFeiertagebefüllen() is not the form's instance you're showing after that. You need to pass the entfernen instance to cbFeiertagebefüllen():
public void cbBefüllen()
{
database.cbFeiertagebefüllen(this);
}
public void cbFeiertagebefüllen(FeiertageEntfernen feiertagentfernen)
{
// Use the passed in instance instead of a newly created one
//FeiertageEntfernen feiertagentfernen = new FeiertageEntfernen();
string Query = #"select bezeichnung from feiertage";
// ....................
}
For this to work, the ComboBox which you need to fill, should be globally declared, i.e. outside the scope of your functions. The rest is probably fine. Also it's better if you get the values you need to display in the comboBox to the main form rather than calling the ComboBox instance 2 levels deeper.
I know this is a little confusing, in simple words, What you could do is, fill the values(descriptions of the holidays) from the DataBase into a list. Make your functions return this list when called. And finally where the ComboBox is declared, you could just add that list as the source of the ComboBox
It looks like you are adding the options to the combo box, but you are not actually setting the selected item.
To do so, you need to set cbFeiertag.SelectedIndex or cbFeiertag.SelectedValue.

RichTextBox.RTF not accepting String generated from Database - C#

I have a bit of a weird problem here. I'm attempting to create a form that, when making a selection from a ListBox, will poll data from a database and display it in a RichTextBox. I need the data to be in RTF for formatting purposes.
It works fine if I do something like this:
private void SaveListTest_SelectedIndexChanged(object sender, EventArgs e)
{
DescriptionName = Convert.ToString(SaveListTest.SelectedItem);
//CallDescriptionTest();
CallDescriptionTest2();
SaveRichTest.Rtf = DescriptionText;
}
public void CallDescriptionTest2()
{
switch (DescriptionName)
{
case "Test":
DescriptionText = #"{\rtf1\ansi\ Test}";
break;
case "Words":
DescriptionText = #"{\rtf1\ansi\ A really long phrase}";
break;
}
}
In such a case, the RichTextBox (SaveRichTest) will take the data and display it just fine.
However, if I do something like this, where the Description column in the database has the text entered exactly as above (ex - #"{\rtf1\ansi\ Test}"):
private void SaveListTest_SelectedIndexChanged(object sender, EventArgs e)
{
DescriptionName = Convert.ToString(SaveListTest.SelectedItem);
CallDescriptionTest();
//CallDescriptionTest2();
SaveRichTest.Rtf = DescriptionText;
}
public void CallDescriptionTest()
{
using (SqlConnection con = new SqlConnection(BuildDB))
{
con.Open();
string sql = String.Format("Select * from Abilities where Name = '{0}'", DescriptionName);
SqlCommand oCmd = new SqlCommand(sql, con);
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
DescriptionText = Convert.ToString(oReader["Description"]);
}
con.Close();
}
}
}
This will instead cause the program to crash, with an error that the "File format is not valid".
I know the text is pulling from the database correctly, because if I change "SaveRichTest.Rtf" to "SaveRichTest.Text", it displays it properly (albeit with the RTF formatting code displayed).
I just can't figure out why it won't take the string properly in the second case. It makes no sense to me whatsoever. Can someone help?
I guess in the case when you tried to show your output in plain text your output was: #"{\rtf1\ansi\ Test}
This would mean when you want to show this string formatted directly from the database you would pass it "#"{\rtf1\ansi\ Test}"" instead of the correct format. I'd suggest you store the format without the # in the database and simply show the result.

How do I prevent button code from running twice if the user clicks more than once in C#?

I have a method where, when the user clicks a button, it selects data from a table and adds it to a text box. The problem is that when a user clicks 2 or more times, the display code runs once for each click and the data is displayed multiple times in the text box.
How can I clear the Text box and display the data only once?
Note: One of the Text boxes by default has a string which I use on a query that gets the data. When I clear the data, the query throws an error since it doesn't have that string I just cleared to finish the query.
This is the code method that I'm using:
private void FillFilds()
{
mycon.Open();
string queryfill= "SELECT *From master where Num=#Num";
oleDbCmd = new OleDbCommand(queryfill, mycon);
oleDbCmd.Parameters.Add("#Lot", OleDbType.VarChar, 40).Value = Numtxt.Text;
OleDbDataReader reader;
try
{
reader = oleDbCmd.ExecuteReader();
reader.Read();
Idlbl.Text += reader[0];
Datetxt.Text += reader[1];
DatePtxt.Value = Convert.ToDateTime(reader[2]);
Jobtxt.Text += reader[3];
NoBtxt.Text += reader[4];
NoPatxt.Text += reader[5];
NoMtxt.Text += reader[6];
Numtxt.Text += reader[7];
NoRtxt.Text += reader[8];
Description.Text += reader[9];
NoMatxt.Text += reader[10];
reader.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
mycon.Close();
}
I think this might clear some questions...
sorry im new at writing in forums.
You could store this default value somewhere, for example as field in the class:
private string DefaultNumber = "12345";
// ...
Then you can assign this value to the TextBox:
Number.Text = DefaultNumber; // instead of Number.Clear() or Number.Text = ""
But you should really use sql-parameters to prevent sql-injection:
string queryfill = "SELECT * From master where Number = #Number";
DataTable table = new DataTable();
using (OleDbConnection conn = new OleDbConnection(ConnString))
using (OleDbDataAdapter da = new OleDbDataAdapter(queryfill, conn))
{
da.SelectCommand.Parameters.AddWithValue("Number", Number.Text);
da.Fill(table);
}
If the text is showing up multiple times in the text box, then you must be appending it rather than setting it. Make sure that you set the .Text value of the textbox using the = sign rather than appending to whatever is there (such as with +=).
You may also want to consider hard coding your default rather than relying on it being displayed in a text box. You can check if the text box is empty or not. If it is empty, then you can use the default, if it is not empty, you can use the entered value. Use String.IsNullOrEmpty(textbox.Text) to check if the string is empty.
You should also note that your code is completely insecure and would allow someone to do anything they wanted with your database through an attack called SQL Injection. You should never allow user input to be passed directly in to a SQL statement. Instead, you should use parameterized SQL and pass the user input as a parameter. This prevents a hacker from being able to insert additional SQL commands in to the input. For example, in this case, if I put '); DROP TABLE Master; SELECT * FROM passwords(' in your textbox, it would destroy your master table.

"Input string was not in a correct format."

I am working on a project in which I have a form through which I can edit a question available in a list view. Whenever I select a row from the list view and click on the 'modify' button, the text boxes above the list view load the question and its options.
This means that when I select a row in the list view and click on the 'modify' button, the question loads itself into the text boxes. I edit the question there and click on 'save' to save changes, but I am not able to access the data in the text boxes. It says {"Input string was not in a correct format."}.
My code of the form frmFormWizard's 'edit' button is given below:
frmFormWizard.cs Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace SurveyBuilder
{
public partial class frmFormWizard : Form
{
int intPanelNumber = 1;
Boolean blnCancel = false;
//int intFlag = 1;
public frmFormWizard()
{
InitializeComponent();
}
...
private void btnEditTwoOrMoreOptions_Click(object sender, EventArgs e)
{
int QuestionID;
string sql;
QuestionID = Convert.ToInt32(lvTwoOrMoreOptions.SelectedItems[0].Text.ToString());
{
SqlConnection cn = new SqlConnection();
SqlCommand rs = new SqlCommand();
SqlDataReader sdr = null;
clsConnection clsCon = new clsConnection();
clsCon.fnc_ConnectToDB(ref cn);
sql = "";
sql += "SELECT * FROM SurveyQuestionLog WHERE SurveyQuestionLog.QuestionLogID = "+ QuestionID +"";
//sql += "SELECT * FROM SurveyQuestionLog";
rs.Connection = cn;
rs.CommandText = sql;
sdr = rs.ExecuteReader();
while (sdr.Read())
{
txtTwoOrMoreQuestions.Text = (string)sdr["Question"];
txtOption1.Text = (string)sdr["Choice1"];
...
}
sdr.Close();
rs = null;
cn.Close();
}
}
Whenever I try to compile the code it says "{"Input string was not in a correct format."}" and this error is shown on the following line:
QuestionID = Convert.ToInt32(lvTwoOrMoreOptions.SelectedItems[0].Text.ToString());
Please let me know what I am doing wrong.
It looks like some space include in the text.
Use
lvTwoOrMoreOptions.SelectedItems[0].Text.ToString().Trim()
and convert to int32.
hope this code will solve you
From comments
if your ListView is in report mode (i.e. it looks like a grid) then you will need the SubItems property. lvTwoOrMoreOptions.SelectedItems gets you each items in the list view - SubItems gets you the columns. So lvTwoOrMoreOptions.SelectedItems[0].SubItems[0] is the first column value,
Please change your code like below.
int QuestionID;
bool IsIntValue = Int32.TryParse("YOUR-VARIABLE", out QuestionID);
if (IsIntValue)
{
// YOUR CODE HERE
}
Hope i will be help.
whenever i try to compile the code it says "{"Input string was not in a correct format."}"
This error won't come on compiling.
Now the error comese because you are trying to parse an invalid string to integer. To do it in a safe manner, you should do it like this
int questionID;
if(int.TryParse(vTwoOrMoreOptions.SelectedItems[0].Text.ToString(),out questionID))
{
//success code
}
else
{
//failure code
}
You might be trying to access a control inside a control, maybe a GridView or DetailsView.
Try using something like this:
empsalary = Convert.ToInt32(((TextBox)DetailsView1.Rows[1].Cells[1].Controls[0]).Text);
It looks that whatever that text is containing some characters which cannot be converted to integer like space, letters, special characters etc. Check what is coming through dropdown as below
lvTwoOrMoreOptions.SelectedItems[0].Text.ToString();
and see if that is the case.

Update Statement

How do I make it possible to update information in a database based on text that is input from another form?
What needs to happen (The forms used are in bold:
StudiesForm User logs in (types username and password in separate textboxes).
The information from the username textbox on the StudiesForm is saved and used as a reference in the select statement for displaying the details on the next form.
UpdateMyDetailsForm User sees their information and can update it.
Here is an attempt, however it calls the first row of data from the database and not the unique individuals.
private void UpdateMyDetailsForm_Load(object sender, EventArgs e)
{ // Select Statement to automatically Load data to the form
//VariableHandler vh = new VariableHandler();
StudiesForm sf = new StudiesForm();
sc.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from StudentRecords where ID ='" + sf.txtBoxUsername + "'", sc);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
comBoxFrm.Text = (myReader["Title"].ToString());
txtBoxFName.Text = (myReader["First_Name"].ToString());
txtBoxSName.Text = (myReader["Surname"].ToString());
txtBoxHouseNum.Text = (myReader["House/Flat_Number"].ToString());
txtBoxStreetName.Text = (myReader["Street_Name"].ToString());
txtBoxTownCity.Text = (myReader["Town/City"].ToString());
txtBoxCounty.Text = (myReader["County"].ToString());
txtBoxPCode.Text = (myReader["Postal_Code"].ToString());
txtBoxPhone.Text = (myReader["Telephone"].ToString());
txtBoxEmail.Text = (myReader["Email"].ToString());
sc.Close();
}// end of select statement
}
Second attempt I tried to save the textbox value from the StudiesForm to a seperate class, then call the variable in the SQL command. Doing this caused the form to show all the details as blank.
I believe the issue is that because the StudiesForm hides after the user has logged in, the reference to the username text box disappears.
I tried to use String.Copy(textbox) to make a unique reference however that also didn't work.
Any ideas or suggestions? - This is also not a serious project so no worries about SQLi attacks or redundant code.
I guess what I'm asking is How Do I Reference A Textbox Value On A Different Form? In C#.
Thanks

Categories

Resources