edit: Solved
I have a label that gets populated with a value from a database. If the user enters this value into a textbox below, I want to change the background. The label displays the value fine on screen, but when I try to match the values in the textbox's textchanged event, it shows as null.
public void button1_Click(object sender, RoutedEventArgs e)
{
txtAnswer.Clear();
txtAnswer.Background = Brushes.White;
int number = r.Next(3) + 1;
string queryEnglish = "SELECT englishVerb FROM verbTable WHERE (verbID = " + number + ")";
string queryFrench = "SELECT frenchVerb FROM verbTable WHERE (verbID = " + number + ")";
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\verbs.mdf;Integrated Security=True;User Instance=True"))
{
con.Open();
using (SqlCommand command = new SqlCommand(queryEnglish, con))
{
this.lblEnglishVerb.Content = (string)command.ExecuteScalar();
}
using (SqlCommand command = new SqlCommand(queryFrench, con))
{
this.lblFrenchVerb.Content = (string)command.ExecuteScalar();
}
}
}
public void txtAnswer_TextChanged(object sender, TextChangedEventArgs e)
{
if (txtAnswer.Text == lblFrenchVerb.Content.ToString())
txtAnswer.Background = Brushes.LightGreen;
if (txtAnswer.Text == "test")
txtAnswer.Background = Brushes.AliceBlue;
}
Textchanged will probably get triggered the moment 'nothing' is placed into the Content. So on the first txtAnswer_TextChanged you might get nothing.
Related
Im writing stock program - just to learn a little bit of c# and i got some problem.
Here is a part of mine code
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
string conString =
"Data Source=192.168.0.195;" +
"Initial Catalog=test;" +
"User id=sa;" +
"Password=12345678;";
string query = "Select * from dokumenty where symbol='" + comboBox_symbol.Text + "' ; ";
SqlConnection conDB = new SqlConnection(conString);
SqlCommand cmdDB = new SqlCommand(query, conDB);
SqlDataReader sqlReader;
try
{
conDB.Open();
sqlReader = cmdDB.ExecuteReader();
while (sqlReader.Read())
{
var s_Typ_dok = sqlReader.GetString(1);
var s_Symbol = sqlReader.GetString(2);
var s_Delivery_date = sqlReader.GetString(3);
var s_Invoice_date = sqlReader.GetString(4);
var s_Invoice_nr = sqlReader.GetInt32(5).ToString();
var s_Sybtype = sqlReader.GetString(6);
var s_Produkt_index = sqlReader.GetString(7);
var s_Produkt_name = sqlReader.GetString(8);
var s_Quantity = sqlReader.GetInt32(9).ToString();
var s_Price = sqlReader.GetString(10);
var s_From_warehouse = sqlReader.GetString(12);
var s_To_warehouse = sqlReader.GetString(13);
var s_Currency = sqlReader.GetString(14);
var s_Supplier_reciever = sqlReader.GetString(15);
comboBox_Type.Text = s_Typ_dok;
textBox_symbol.Text = s_Symbol;
textBox_deliveryDate.Text = s_Delivery_date;
textBox_invoiceDate.Text = s_Invoice_date;
textBox_invoice.Text = s_Invoice_nr;
textBox_subtype.Text = s_Sybtype;
textBox_produkt_index.Text = s_Produkt_index;
textBox_name.Text = s_Produkt_name;
textBox_quantity.Text = s_Quantity;
textBox_price.Text = s_Price;
comboBox_from_warehouse.Text = s_From_warehouse;
comboBox_to_warehouse.Text = s_To_warehouse;
comboBox_currency.Text = s_Currency;
textBox_supplier.Text = s_Supplier_reciever;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
which works ok, when i selected something in combobox5 it auto insert things to Textboxes when it exist in DB, but when i erase this thing which i select in combobox5, text in textboxes is still there. Is there any chance to erase it when combobox5 == null?
On SelectedIndexChanged event add one condition to check SelectedIndex==0, if selected index is zero then clear text of Text box,
If you don't wants to edit text from combo box then you can set combobox as non editable by setting
comboBox5.DropDownStyle = ComboBoxStyle.DropDownList;
This will not allow user to edit text from combobox
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox5.SelectedIndex==0)
{
TextBoxId.Text=String.Empty;
}
else
{
//Rest of your code here
}
}
Hello all just an update, I am still facing the issues of getting the chart to display the correct number of records. I have discovered where the chart is currently getting it's numbers from however it makes no sense as to why it is using those numbers. It is from a column in the database called "mpm_code" however I have never specified for the chart to use those numbers. Here are the numbers in the database:
Here is the chart
And here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace RRAS
{
public partial class formRRAS : Form
{
public OleDbConnection DataConnection = new OleDbConnection();
string cmbRFR_item;
public formRRAS()
{
InitializeComponent();
}
//When the form loads it sets the intial combo box RFR item to null
private void formRRAS_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.tblReject_test' table. You can move, or remove it, as needed.
this.tblReject_testTableAdapter.Fill(this.database1DataSet.tblReject_test);
cmbRFR.SelectedItem = "";
this.AcceptButton = btnSearch;
}
//AddRFR method, called in the NewRFRPopup
public void AddRFR(object item)
{
cmbRFR.Items.Add(item);
}
private void change_cmbSubRFR_items()
{
cmbSubRFR.Items.Clear();//Clear all items in cmbSubRFR comboBox.
switch (cmbRFR_item)//Adding your new items to cmbSubRFR.
{
case "":
cmbSubRFR.Items.Add("");
cmbSubRFR.Text = "";
break;
case "POSITIONING":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Anatomy cut-off");
cmbSubRFR.Items.Add("Rotation");
cmbSubRFR.Items.Add("Obstructed view");
cmbSubRFR.Items.Add("Tube or grid centering");
cmbSubRFR.Items.Add("Motion");
cmbSubRFR.Text = "";
break;
case "ARTEFACT":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("ARTEFACT");
cmbSubRFR.Text = "ARTEFACT";
cmbSubRFR.Text = "";
break;
case "PATIENT ID":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Incorrect Patient");
cmbSubRFR.Items.Add("Incorrect Study/Side");
cmbSubRFR.Items.Add("User Defined Error");
cmbSubRFR.Text = "";
break;
case "EXPOSURE ERROR":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Under Exposure");
cmbSubRFR.Items.Add("Over Exposure");
cmbSubRFR.Items.Add("Exposure Malfunction");
cmbSubRFR.Text = "";
break;
case "TEST IMAGES":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Quality Control");
cmbSubRFR.Items.Add("Service/Test");
cmbSubRFR.Text = "";
break;
}
}
private void cmbRFR_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbRFR_item != cmbRFR.SelectedItem.ToString())//This controls the changes in cmbRFR about selected item and call change_cmbSubRFR_items()
{
cmbRFR_item = cmbRFR.SelectedItem.ToString();
change_cmbSubRFR_items();
}
}
//The code for the button that closes the application
private void btnSearch_Click(object sender, EventArgs e)
{
//This creates the String Publisher which grabs the information from the combo box on the form.
//Select and Dataconnection are also defined here.
string Department = String.IsNullOrEmpty(txtDepartment.Text) ? "%" : txtDepartment.Text;
string Start_Date = String.IsNullOrEmpty(txtStart.Text) ? "%" : txtStart.Text;
string End_Date = String.IsNullOrEmpty(txtEnd.Text) ? "%" : txtEnd.Text;
string Anatomy = String.IsNullOrEmpty(txtAnatomy.Text) ? "%" : txtAnatomy.Text;
string RFR = String.IsNullOrEmpty(cmbRFR.Text) ? "%" : cmbRFR.Text;
string Comment = String.IsNullOrEmpty(cmbSubRFR.Text) ? "%" : cmbSubRFR.Text;
string Select = "SELECT * FROM tblReject_test WHERE department_id LIKE '" + Department + "'" + "AND body_part_examined LIKE'" + Anatomy + "'" + "AND study_date LIKE'" + Start_Date + "'" + "AND study_date LIKE'" + End_Date + "'" + "AND reject_category LIKE'" + RFR + "'" + "AND reject_comment LIKE'" + Comment + "'";
//DataConnection connects to the database.
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
//The DataAdapter is the code that ensures both the data in the Select and DataConnection strings match.
OleDbDataAdapter rdDataAdapter = new OleDbDataAdapter(Select, DataConnection);
try
{
//It then clears the datagridview and loads the data that has been selected from the DataAdapter.
database1DataSet.tblReject_test.Clear();
rdDataAdapter.Fill(this.database1DataSet.tblReject_test);
}
catch (OleDbException exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}
} //End of Search button
//Temporary button thats loads the chart when clicked
private void btnLoadChart_Click(object sender, EventArgs e)
{
charRejections.Series["RFR"].Points.Clear();
{
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
try
{
int count = database1DataSet.Tables["tblReject_test"].Rows.Count;
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT COUNT(*) as count, reject_category FROM tblReject_test GROUP BY reject_category";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader[count]);
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
} //end of load chart button
//These buttons are all from the file menu bar
//A simple button that closes the application
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
//This button loads the NewRFRPopup form
private void addRFRToolStripMenuItem_Click(object sender, EventArgs e)
{
NewRFRPopup popup = new NewRFRPopup(this);
popup.ShowDialog();
}
private void printChartToolStripMenuItem_Click(object sender, EventArgs e)
{
charRejections.Printing.PrintDocument.DefaultPageSettings.Landscape = true;
charRejections.Printing.PrintPreview();
}
//End of file menu bar
//These buttons change the format of the chart
private void btnPie_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Pie;
}
private void btnBar_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
}
private void btnSideways_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Bar;
}
private void btnLine_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
}
//end of chart formatting
}
}
The Issue has been sorted thanks to a friend of mine. This relates to the code that TaW posted the other day. Thanks for everyone's time and suggestions. The fixed code is below:
private void btnLoadChart_Click(object sender, EventArgs e)
{
charRejections.Series["RFR"].Points.Clear();
{
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
try
{
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT COUNT(reject_category) as reject, reject_category FROM tblReject_test GROUP BY reject_category";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader["reject"].ToString());
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}//end of load chart button
I want to update this form's Login and Logout Time:
My code is :
protected void btnUpdate_Click(object sender, EventArgs e)
{
string LoginTime = txtIn.Text;
string LogOutTime = txtOut.Text;
long DayLogId = Convert.ToInt64(Request.QueryString["ID"]);
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =#"Data Source=DELL\SQLSERVER1;Initial Catalog=LoginSystem;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("UPDATE [DayLog] SET [LoginTime]=#LoginTime,[LogOutTime]=#LogOutTime WHERE [DayLogId]=#DayLogId");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#LoginTime", LoginTime);
dataCommand.Parameters.AddWithValue("#LogOutTime", LogOutTime);
dataCommand.Parameters.AddWithValue("#DayLogId", DayLogId);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
At the first two lines of method ,
string LoginTime = txtIn.Text;
string LogOutTime = txtOut.Text;
when I debug , it does not show the value that I reinserted. This code works if I mannually write
string LoginTime = "11:44:11";
string LogOutTime = "12:44:11";
NOTE:
The value of forms in text box is coming from another page GridView.
protected void grdEmployee_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
GridViewRow grRow = ((Control)e.CommandSource).NamingContainer as GridViewRow;
Label DayLogId = grRow.FindControl("lblDayLogId") as Label;
if (Convert.ToInt16(DayLogId.Text) > 0)
{
Response.Redirect("~/Employee/OutLog_Day.aspx?ID=" + DayLogId.Text, false);
}
}
}
You should make sure that the text box gets populated before the click event runs. As Steve suggested, usually you get this when you initialize the data on every postback which is unnecessary if the data is not changed.
A user inputs a keyword into a textbox which must be searched in the database which is connected to c# using Connection String, I want to search in the database and display all the possible occurrence of the keyword which the user inputs.
After clicking the button, I get the error message "Object reference not set to an instance of an object" which points to the line "ResultsQuery = Request.QueryString[TextBox1.Text].Split(' ');"
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();
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();
}
Check to see if the query string value exists before you try and retrieve it, like this:
if (Request.QueryString[TextBox1.Text] != null) {
ResultsQuery = Request.QueryString[TextBox1.Text].Split(' ');
}
I'm currently trying to find a textbox control in InsertItemTemplate to test against values already in one of my database tables but I can't seem to get the FindControl to work. Below is the code I'm currently looking at:
protected void InsertButton_Click(object sender, EventArgs e)
{
TextBox linkinsTextBox = Page.FindControl("linkinsTextBox") as TextBox;
String connectionString = WebConfigurationManager.ConnectionStrings["UniString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
bool exists = false;
//The number of entries in links is counted
String linkCountQuery = " SELECT COUNT(link) from[links] where link = " + linkinsTextBox.Text + "";
SqlCommand linkCountQueryCommand = new SqlCommand(linkCountQuery, myConnection);
Int32 linkCountQueryCommandValue = (Int32)linkCountQueryCommand.ExecuteScalar();
myConnection.Close();
if (linkCountQueryCommandValue >= 1)
{
exists = true;
URLexists.Text = "URL already exists. Please enter a different URL.";
}
}