Method changed string values are not showing up in data-bound textboxes - c#

So I have a class and a form.
The class hosts the MySQL code and the form holds the events that trigger the code in the MySQL class
// Code that acceses the class
// This triggers a method that is supposed to get the next record from the database.
private void next_Click(object sender, RoutedEventArgs e)
{
// Tag.text is the auto incremented unique record number.
// The MySQL code is meant to get the next record ahead of the number in tag.text
// in the corresponding table field.
usersMysql.RegForm_Next(tag.Text);
}
this next part is the method that accesses the MySQL code meant to fetch the next record
public void RegForm_Next(string tag_Value)
{
// tagValue now holds the number, which was in tag.text in the previous page, as a string
// tagValue has already been predeclared as a string
tagValue = tag_Value;
// Navigation is the method that holds the MySQL code.
// By passing "Forward", the method has a code to tell from that, which query to excecute.
Navigation("Forward");
}
The next code is the MySQL code meant to fetch the record
// Command to go to the next or previous rexord
public void Navigation(string scroll)
{
if (scroll == "Forward")
{
query = "select * from temp.signup where tag = (select min(tag) from temp.signup where tag > '" + tagValue + "' );";
}
if (scroll == "Backward")
{
query = "select * from temp.signup where tag = (select max(tag) from temp.signup where tag < '" + tagValue + "' );";
}
//Database connection parameters
string sqlcon = "datasource = " + datasource + ";" + "port=" + port + ";" + "username=" + username + ";" + "password=" + password + ";";
MySqlConnection con = new MySqlConnection(sqlcon);
MySqlDataReader rdr;
MySqlCommand cmd = new MySqlCommand(query, con);
//Excecution
try
{
//If the connection is Open
con.Open();
{
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
// Declarations
// All these strings have been declared under the public class declaration.
sid = GetString(rdr, "id");
stag = GetColumnValueAsString(rdr, "tag");
sfirst = GetString(rdr, "first");
sfourth = GetString(rdr, "surname");
sdob = rdr.GetString("dob");
ssex = rdr.GetString("sex");
susername = GetString(rdr, "username");
spassword = GetString(rdr, "password");
}
con.Close();
}
}
catch (Exception ex)
{
ModernDialog.ShowMessage(ex.Message, "SQL related error: Nav", MessageBoxButton.OK);
}
}
Now this where the problem comes in. I need to bind the strings values to textboxes back in the previous page that called the method in the MySQL class up.
// This is how the ID binding was set up for example.
// This is where sid was declared.
string sid;
public string ID
{
get
{
return sid;
}
set
{
sid = value;
RaisePropertyChanged("ID");
}
}
And this is how the textbox binding was set up
<TextBox x:Name="id" Text="{Binding ID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged }" Margin="158,46,453,468" FontSize="13" TabIndex="1" />
I've set the data context in the page wit the textboxes but the strings are never loaded back into the textbox
public registrationForm()
{
InitializeComponent();
usersMysql = new users.MySQL.usersMySQL();
DataContext = usersMysql;
}
I can confirm that the strings are being loaded. I've tested with a message box. But nothing shows up in the text boxes.
This is the function I use for "propertyChanged" in the class
//Property changed
private void RaisePropertyChanged(string prop)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
public event PropertyChangedEventHandler PropertyChanged;
If I bind two textBoxes to the same public string, they reflect what is being typed in the other. Where am I going wrong then?

Your code is changing the sid backing field, not the ID property.
Therefore, the PropertyChanged event is never fired, and WPF never finds out about the change.

Related

Form get blank when Page_Load function is called?

I am facing a problem in my form. There are two text field and then there is drop-down menu, which link to a database.
When I click on the drop down menu, my two text fields are getting empty.
protected void OnChange_Acdemics(object Sender, EventArgs e)
{
DropDownList list = (DropDownList)Sender;
string value = (string)list.SelectedValue;
// degrees_dropdown.Visible = true;
try
{
// String query = "SELECT Degree_types.detail,Degree_Detail.GPA FROM Degree_Detail INNER JOIN Degree_types ON Degree_Detail.Degree_tilte = Degree_types.Degree_title where Degree_types.degree_type = '" + value + "';";
String query = "Select detail from Degree_Detail where id=" + int.Parse(value) + ";";
Dt = dbComm.GetDataTable(query);
Degree_Selection.DataTextField = "detail";
// Degree_Selection.DataValueField = "GPA";
Degree_Selection.DataSource = Dt;
Degree_Selection.DataBind();
}
catch (Exception ex)
{
}
}
You need to take care of this by using Page.IsPostBack:
if(!Page.IsPostBack)
{
// load page
}
else
{
// check input values and set it again
}

Using textbox value for a class

i'm trying to use my Textbox value from another form to a class to insert items to my database.
I tried creating another instance of my Form1 which is the name of the form I want to get the value from but it returns 0 items to my database when I click my submit button is there anyway to do this?
public void Insert()
{
Form1 mform = new Form1();
string query = "INSERT INTO parts (item_id, description, brand, model, color, quantity) VALUES('0', '"
+ mform.Description.Text
+ "','" + mform.Brand.Text
+ "','" + mform.Model.Text
+ "','" + mform.Color.Text
+ "','" + mform.Quantity.Text + "')";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
}
When you instantiate a new instance of the Form1() object, you are assuming that the new instance's "Description, Brand, Model, Color and Quantity" TextBox's contains text? The default value of a TextBox.Text is the default value of its string property type, null.
Ideally, you will take the values that the user has populated from the form instance and then pass them into the DB like so:
public void Insert()
{
using (var mform = new Form1())
{
// Ensure that the user entered values...
if (mform.ShowDialog() == DialogResult.Ok)
{
string query = "INSERT INTO parts (item_id, description, brand, model, color, quantity) VALUES('0', '"
+ mform.Description.Text
+ "','" + mform.Brand.Text
+ "','" + mform.Model.Text
+ "','" + mform.Color.Text
+ "','" + mform.Quantity.Text + "')";
if (this.OpenConnection() == true)
{
var cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
}
}
}
Additionally, you should avoid inline SQL and instead use stored procedures, or at the very least use SqlParameter's.
No, you cannot access Form1 values in a class by creating new instance. To access textbox values you need to do the following:
Create public property in a class
Assign property with textbox value in some appropriate event (such as TextChanged)
Access property inside class to get textbox value and save it to database.
Example
Class:
public class DataAccess
{
public string IncomingValue { get; set; }
public string SaveToDatabase()
{
string valueToSave = IncomingValue;
// Insert into database
return "Success";
}
}
Form:
DataAccess access = new DataAccess();
private void textBox1_TextChanged(object sender, EventArgs e)
{
access.IncomingValue = textBox1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(access.SaveToDatabase());
}
Also, I would suggest you to use Parametrized Query. This will give you more readability and saves you from SQL injection and confusion.

C# Passing Values between dependent Comboboxes

I'm relatively new but I've been researching this issue for over 2 days, so I think I've done my due diligence ... however if this has already been answered before I apologize.
My basic issue is I'm trying to create some dependent combo boxes. The wrinkle is the displayed value is typically not the lookup value for the next query/Combo box (I'm using an OLEDB compliant data base)
For example: Table1 (T1) contains ID (int) & NM (string), Table2 (T2) contains ID (int) & STATUS (string). I run Query1 (Q1) to display T1.NM in Combobox1 (CB1), when selected I run Query1a to lookup/get the selected Table1.ID to pass to Query2 that populates Combobox2. The connection string and Q1 work fine, CB1 displays properly, but once I select this error is thrown:
"OleDbException .. SQL Passthru expression ... using equals (=) has components that are of different data types"
// ** Initial connection & populate CB1 - This works fine **
public void comboboxLoad()
{
string conn3str = <Connection String >;
string query1 = "select NM from Table1 where REFVALUE=1 ; ";
OleDbConnection conn3 = new OleDbConnection(conn3str);
OleDbCommand tblRow1 = new OleDbCommand(query1, conn3);
OleDbDataReader rdRow1;
try
{
conn3.Open();
lblConnState.Text = "Connection Successful";
rdRow1 = tblRow1.ExecuteReader();
while (rdRow1.Read())
{
int colindx1 = rdRow1.GetOrdinal("NM");
string sItbl = rdRow1.GetString(colindx1);
CB1.Items.Add(sItbl);
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
// ** Get value from CB1, create query to populate CB2 **
private void CB1_SelectedIndexChanged(object sender, EventArgs e)
{
string conn3str = <Connection String >;
OleDbConnection conn3 = new OleDbConnection(conn3str);
conn3.Open();
// Pass the selected value from CB1 (string) equal to Table1.NM (string)
string query1a = "select ID from Table1 where NM = '" + CB1.Text + "' ; ";
OleDbCommand TabID = new OleDbCommand(query1a, conn3);
int TabId2 = Convert.ToInt32(TabID.ExecuteScalar());
// Pass the variable TabId2 (int) equal to Table2.ID (int)
string query2 = "select STATUS from Table2 where ID = '" + TabId2 + "'; ";
OleDbCommand tblRow2 = new OleDbCommand(query2, conn3);
// OleDbDataReader rdTabID;
// OleDbDataReader rdRow2;
try
{
OleDbDataReader rdRow2 = TabID.ExecuteReader();
OleDbDataReader rdTabID = tblRow2.ExecuteReader(); // ** Error points to this line **
while (rdRow2.Read())
{
int TabIdidx = rdTabID.GetOrdinal("ID");
string TabIDVal = rdTabID.GetString(TabIdidx);
// Pass reference ID to label on form
lblBTableID.Text = TabId2.ToString();
int colindx1 = rdRow2.GetOrdinal("STATUS");
string sIntVal = rdRow2.GetString(colindx1);
cmbLowLvl.Items.Add(sIntVal);
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
Are you positive you're getting a value back on this line int TabId2 = Convert.ToInt32(TabID.ExecuteScalar());?
Convert.ToInt32 doesn't throw a ArgumentNullException like int.Parse does so it's possible that the variable is not getting set.
Also you may want to consider changing your queries to use parameterized SQL rather than concatenation for security purposes.
https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters(v=vs.110).aspx
I've been able to figure out the problem. I'm really not sure why it didn't work originally, but I think it was a reader mismatch, since I was only looking for a single value back from the query ExecuteScalar() seemed to do the trick and I didn't need the 'while' loop. The working code is below.
Next I'll need to pass this return value (ID) in my next query to populate CB2. Thanks #
private void CB1_SelectedIndexChanged(object sender, EventArgs e)
{
string conn3str = <Connection String >;
OleDbConnection conn3 = new OleDbConnection(conn3str);
// Pass the selected value from CB1 (string) equal to Table1.NM (string) but return the int ID.
OleDbCommand tblRow2 = new OleDbCommand("select ID from Table1 where NM= '"+ CB1.Text +"' ;" , conn3);
try
{
conn3.Open();
string r2 = Convert.ToString(tblRow2.ExecuteScalar());
MessageBox.Show(r2);
lblBTableID.Text = "ID Code= " + r2;
conn3.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}

How to display items in CheckListBox from ComboBox

I have a comboBox and a checkListBox in my windows form application that connected to my SQL database. I got the binding data part working, but I am not sure how to show the datas in checkListBox when the comboBox item is selected. Let say I have 10 items in my comboBox that bind with my SQL database and they are under the column name ("application name ") such as excel, word, android, eclipse etc.... I call this method when the form begin to load. Sorry for the long code.
Here is my code for that applicationComboBox
private void loadComboBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
myConn.Open();
//my table name is Application_Detail
string query = "select * from Application_Detail";
myCommand = new SqlCommand(query, myConn);
//reading the value from the query
SqlDataReader dr = myCommand.ExecuteReader();
//Reading all the value one by one
while (dr.Read())
{
//column is 1 in Application_Detail Data
//GetString(1) display the 2nd column of the table
string name = dr.GetString(1);
//display the application name in column 2 -
applicationComboBox.Items.Add(name);
}
myConn.Close();
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The outcome of this part of code is:
//label Name //Application Name
Application Name:
Excel
Word
NotePad
PowerPoint
SubLime
Eclipse
After I call this method, I want to display the teacher name that is according to what the user selected in this applicationComboBox. So if teacher 1,2,3 is using Excel and the user selected excel from the comboBox, the checkListBox will display teacher 1,2,3 and vice versa. To do this, I call the method at the comboBox1_SelectedIndexChanged method because I want to display the detail when I select an item from the comboBox. Below is my code
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
//I check if the comboBox index is at 0, it disable the button.
if (applicationComboBox.SelectedIndex == 0)
{
exportButton.Enabled = false;
this.teacherCheckListBox.DataSource = null;
teacherCheckListBox.Items.Clear();
}
//it it is not at 0,
else
{
exportButton.Enabled = true;
//call this method
fill_checkListBox();
}
//teacherCheckListBox
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void fill_checkListBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
myConn.Open();
//for reading purpose, I break down by long statement
//In this statement, I left join 3 table (Teacher_Detail, AppUser_Detail, and Application_Detail table). My AppUser_Detail contains all 3 id (teacherId, applicationId, and AppUserId). I then set filter the table using `where` keyWord to make the applicationId = the comboBox text
string query = "SELECT
td.chineseName,
ad.applicationId,
aud.applicationId,
ad.applicationName
FROM[AppUser_Detail] as aud
LEFT JOIN[Teacher_Detail] as td
ON aud.teacherId = td.teacherId
LEFT JOIN[Application_Detail] as ad
ON aud.applicationId = ad.applicationId
where aud.applicationId = '" + applicationComboBox.Text + "' AND NOT(td.teacherId IS NULL)
";
myCommand = new SqlCommand(query, myConn);
//reading the value from the query
SqlDataReader dr = myCommand.ExecuteReader();
//Reading all the value one by one
while (dr.Read())
{
//column is 0 where the teacherName belong in my Teacher_Detail table
string name = dr.GetString(0);
//I tried to set the text of the checkListBox as the teacherName, but I can't somehow
teacherCheckListBox.Text = name;
}
myConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
When I run the program like this, it said Conversion failed when converting the varchar value "Excel" to data type int. Is there a way to fix it? it shouldn't be a problem because in my Application_Detail table, my applicationName's and my teacherName's data type is set as nvarchar(50) and applicationId and teacherId = int;
The problem is with this line, I would think:
where aud.applicationId = '" + applicationComboBox.Text +
Based on your code, I would think that applicationId is an int and applicationComboBox.Text is just that, text.
Try this:
where ad.applicationName = '" + applicationComboBox.Text.Trim() +
Try this:
if (string.IsNullOrWhiteSpace(teacherCheckListBox.FindString(name))
{
teacherCheckListBox.Items.Add(name);
}

i want to search the database of what the user entered and display all the possible occurrence of the word

public string[] ResultsQuery;
public int i;
public string criteria;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string connString = #"Data Source=ITLAPTOP\SQLEXPRESS;Initial Catalog=trial;Integrated Security=True";
SqlConnection connStudent = new SqlConnection(connString);
connStudent.Open();
if (Request.QueryString[TextBox1.Text] != null)
{
ResultsQuery = Request.QueryString[TextBox1.Text].Split(' ');
foreach (string textbox1 in ResultsQuery)
{
if (!string.IsNullOrEmpty(criteria))
criteria += " OR ";
criteria += "SearchName LIKE '%" + textbox1 + "%' ";
}
string SqlInsertStatement = #"select * from trial.dbo.Student where Student.SearchName where '" + criteria;
SqlCommand cmdTxt = new SqlCommand(SqlInsertStatement, connStudent);
SqlDataReader dtrACode = cmdTxt.ExecuteReader();
dtrACode.Read();
try
{
if ((dtrACode["SearchName"].ToString().Trim().Length != 0))
{
}
ListBox1.Items.Add(dtrACode["SearchName"].ToString());
}
catch (Exception)
{
ListBox1.Items.Add("NO RECORD FOUND!");
}
connStudent.Close();
connStudent.Dispose();
}
}
i want to display all occurrence of the keyword the user input, for example
list in database:
abCARdfg
CARsdg
CAR
dfgsd
sdkgs
== when i search the word CAR all the string with CAR should be displayed and dfgsd,sdkgs will not be displayed
the query is working just like what i was expecting the SQL server to display but i dont know where to place it in the code in c#, and when i click the button it does not display anything even the NO RECORD FOUND which serves as a error handler
Since I dont have access to your code, my best guess is that you have an error with the following line:
string SqlInsertStatement = #"select * from trial.dbo.Student where Student.SearchName where '" + criteria;
Replace that with the following:
string SqlInsertStatement = #"select * from trial.dbo.Student where " + criteria;
Remove the try/catch and post the details of the Exception that is thrown. There is definately an error in your query. For example, you repeat a "where".
where Student.SearchName where
Also, your code has SQL injection vulnerability in that the textbox1 value can contain anything and is not escaped. For example, a person can type '; -- delete from TABLE;
and delete everything in your table...

Categories

Resources