database values in textbox - c#

If the voucher number that I typed exists in the table, it should show the details in the respective textboxes, but if it doesn't exist a message box that says (ID doesn't exists! ) would show.
For example, the voucher number 101 exists in the table,
First,I would type '1' in the textbox , the messagebox would immediately appear ...
Second I would continue the number after clicking ok it will now be number "10" a messagebox will again appear that says (ID doesn't exists! ). Then finally I would be able to type "101" the details would already show in the respective textboxes.
My problem is that when everytime that I typed a single number, a messagebox that says (ID doesn't exists! ) appears. How do I solve that?
textchanged property of "textBox22" code:
private void textBox22_TextChanged(object sender, EventArgs e)
{
String path = "Data Source=LOCALHOST; Initial Catalog= sadd; username=root; password=''";
MySqlConnection sqlconn = new MySqlConnection(path); //communicator //constructors
MySqlCommand sqlcomm = new MySqlCommand();
MySqlDataReader sqldr;
sqlconn.Open();
sqlcomm.Connection = sqlconn;
sqlcomm.CommandType = CommandType.Text;
sqlcomm.CommandText = "Select * from approvedrecords where VoucherNumber=" + textBox22.Text + "";
sqldr = sqlcomm.ExecuteReader();
sqldr.Read();
if (sqldr.HasRows)
{
textBox26.Text = sqldr[0].ToString();
}
sqlconn.Close();
if (textBox22.Text == textBox26.Text)
{
String path8 = "Data Source=LOCALHOST; Initial Catalog= sadd; username=root; password=''";
MySqlConnection sqlcon = new MySqlConnection(path8); //communicator //constructors
string query = "select * from approvedrecords where VoucherNumber = " + textBox22.Text + " ";
MySqlCommand cmd = new MySqlCommand(query, sqlcon);
MySqlDataReader dbr;
sqlcon.Open();
dbr = cmd.ExecuteReader();
while (dbr.Read())
{
string a = (string)dbr["CheckNumber"].ToString();
string b = (string)dbr["DateCreated"];
string c = (string)dbr["Status"];
string d = (string)dbr["PayeesName"];
string f = (string)dbr["Amount"].ToString();
string g = (string)dbr["DatePrinted"];
string h = (string)dbr["Particulars"];
string i = (string)dbr["Prepared_by"];
string j = (string)dbr["Payment_received_by"];
textBox21.Text = a;
textBox23.Text = b;
textBox28.Text = c;
textBox20.Text = d;
textBox19.Text = f;
textBox27.Text = g;
textBox18.Text = h;
textBox16.Text = i;
textBox17.Text = j;
}
}
else
{
MessageBox.Show("ID doesn't exist!");
}

Why don't you try using the OnLostFocus event of the textbox? As explained here. That way your code would be called only when the user abandons your textbox.
Alternatively, if you want to keep your OnTextChanged handler, I would recommend using async calls my adding an UpdatePanel as explained here. You would need to add a label showing the status of the query every time the user typed in a character, so when no data is returned by your query, the label would show "No results found for this ID" and no textboxes would be populated. When results are found, then the label would read "Data was found for this ID" and you would populate the controls accordingly.
I hope this helps and I hope I was clear :-)

Related

Issue with checking DropDownList's Selected Value exist in Database or Not

I have a web page and there I have fields to hold some data.
One of the fields holds the IDs and names of students enrolled in a particular course. I want to be able to enroll new students to the course using a drop-down list. If the item selected in the drop-down list already exists in the Courses Table, I should display an error message.
I have a code to do these but when I select an already existing value in the drop-down list it doesn't show an error message. It assumes it's a new value and throws an exception because the Database doesn't accept duplicate records.
How can I solve this problem?
I use c# language to design this web page in ASP.NET.
protected void DropDownList1_SelectedIndexChanged(object sender,
EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Ceng.mdf;Integrated Security=True");
string qs = Request.QueryString["id"];
// Variable qs Keeps CourseID retrieved from query string
string sv = DropDownList1.SelectedItem.Value;
// Variable sv keeps selected value from DropDownList
SqlCommand cmd = new SqlCommand("Select * from Enrolment as e, Students as s where e.StudentID = s.StudentID and " +
"CourseID = " + qs + " and StudentName = '" + sv +"'", con);
// There are Students, Courses, and Enrolment tables in database
// Students table columns are StudentID, StudentName, BirthDate
// Course table columns are CourseID, CourseCode, CourseName, Instructor
// Enrolment table columns are CourseID and StudentID
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if(reader.HasRows)
{
Label1.Visible = true;
Label1.Text = "The selected student is already registered to the course!";
Label1.ForeColor = Color.Red;
}
else
{
Label1.Visible = true;
Label1.Text = "The selected student is succesfully registered!";
Label1.ForeColor = Color.Green;
SqlDataSource4.Insert();
GridView1.DataBind();
}
reader.Close();
con.Close();
}
When i select a name from DropDownList which is not exist in Database, i get proper result.
For example, Think about "Jeff Bezos" is already registered for given course. When i choose "Jeff Bezos" i should get error message but I get exception which says that is duplicate.
Parameterize the sql
Make the sql a string/text and use it
Get rid if bad associative join, create a INNER instead
use a using which implements idisposable
Assumptions since you did not post the source of the list
Broad assumption on the int vs string for id (int is most common so I go with that)
Suggest this might be refactored to methods for better testing
using System;
using System.Data.SqlClient;
// more here likely...
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Ceng.mdf;Integrated Security=True";
string getStudentIdSql = #"
SELECT s.StudentID
FROM Enrolment AS e
INNER JOIN Students AS s
ON e.StudentID = s.StudentID
AND E.CourseID = #CourseID
AND StudentName = #StudentName
";
int courseId = int.Parse(Request.QueryString["id"]); // consider tryparse here, I make assumptions on the int also
// string studentName = DropDownList1.SelectedItem.Value; // assumption if the values are there
string studentName = DropDownList1.SelectedItem.Text; // assumption based on code/comments, key part where it is defined is missing from question
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(getStudentIdSql, conn))
{
cmd.Parameters.Add("#CourseID", SqlDbType.Int).Value = courseId;
cmd.Parameters.Add("#StudentName", SqlDbType.VarChar, 80).Value = studentName;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
/* if we wanted to have the rows
while (reader.Read())
{
Console.WriteLine($"{reader.GetInt32(0)}\t{ reader.GetString(1)}");
}
*/
Label1.Visible = true;
Label1.Text = "The selected student is already registered to the course!";
Label1.ForeColor = Color.Red;
}
/* basic thing
else
{
Console.WriteLine("No rows found.");
}
*/
else
{
Label1.Visible = true;
Label1.Text = "The selected student is succesfully registered!";
Label1.ForeColor = Color.Green;
SqlDataSource4.Insert();
GridView1.DataBind();
}
reader.Close();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender,
EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Ceng.mdf;Integrated Security=True");
int selectedCourseId = 0;
string qs = Request.QueryString["id"];
int.TryParse(qs, out selectedCourseId);
string sv = DropDownList1.SelectedItem.Value;
SqlCommand cmd = new SqlCommand("Select * from Enrolment as e, Students as s where e.StudentID = s.StudentID and " +
"e.CourseID = #CourseID and s.StudentName = #StudentName", con);
cmd.Parameters.Add("#CourseID", SqlDbType.Int).Value = selectedCourseId;
cmd.Parameters.Add("#StudentName", SqlDbType.NVarChar).Value = sv;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if(reader.HasRows)
{
Label1.Visible = true;
Label1.Text = "The selected student is already registered to the course!";
Label1.ForeColor = Color.Red;
}
else
{
Label1.Visible = true;
Label1.Text = "The selected student is succesfully registered!";
Label1.ForeColor = Color.Green;
SqlDataSource4.Insert();
GridView1.DataBind();
}
reader.Close();
con.Close();
}

how to create an id to be shown in the text box based on selected dropdownlist

i would like to create an id generator based on their department selected from the dropdownlist. lets say my ddl has 3 departments (A,B,C) and when generating an id it will be A20181001 and then A20181002 upon submission but when i pick B from the ddl after sending A20181001 to the database, it will be B20181001.
so far i have created the code for the increment for the id without the departments. here is the code i did so far. (I used the date for today so the 20181001 is just an example):
void getMRF_No()
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
int mrf = 0;
int i;
string a;
//string x = Request.QueryString["BUnit"];
string mrfNo = "";
database db = new database();
string conn = dbe.BU();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand cmd = connUser.CreateCommand();
SqlDataReader sdr = null;
string query = "SELECT TOP 1 MRF_NO FROM incMRF ORDER BY MRF_NO DESC";
connUser.Open();
cmd.CommandText = query;
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr.GetInt32(0).ToString();
}
if (mrfNo == "")
{
mrfNo = Convert.ToString(year) + "" + 00;
}
mrf += 0;
i = Convert.ToInt32(mrfNo) + 1;
a = i.ToString();
txtMRFNo.Text = a;
connUser.Close();
}
any help to improve this code will be helpful. thank you :)
EDIT:
here is the dropdown list code:
void SelectBU()
{
string database = dbe.BU ();
using (SqlConnection con = new SqlConnection(database))
{
con.Open();
string query = "select BUnit from BusinessUnit";
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
DataSet ds = new DataSet();
sda.Fill(ds, "BUnit");
ddlBu.DataSource = ds;
ddlBu.DataTextField = "BUnit";
ddlBu.DataValueField = "BUnit";
ddlBu.DataBind();
selectOption(ddlBu, "Select Dept");
}
con.Close();
}
}
EDIT2: I will state what im searching for here incase some doesnt know or understand. What i want is upon selecting a department from a dropdownlist, for example i picked A. the textbox show show A2018102201. if i select B it should show B2018102201 and if its C then c2018102201. and it will change its number once i submit it to a database and a new form loads. So if A2018102201 is already in the database, then the text shown in the text box will be A2018102202. BUT if i select B then the textbox will show B2018102201 since it does not exist in the database yet.
First you should get max ID, then increase the numeric part of your Id, and If this is a multi-user application, you have to lock your table, because it might create many ID duplication, Therefore I'm not recommend to create ID like this on c#, it is better to create a Sequence on SQL server. but I wrote this sample for you, just call it with proper value.
static string getMRF_No(string prefixCharFromDropDownList)
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
string mrfNo = "";
SqlConnection connUser = new SqlConnection("Server=130.185.76.162;Database=StackOverflow;UID=sa;PWD=$1#mssqlICW;connect timeout=10000");
SqlCommand cmd = new SqlCommand(
$"SELECT MAX(MRF_NO) as MaxID FROM incMRF where MRF_NO like '{prefixCharFromDropDownList}%'"
,connUser
);
connUser.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr["MaxID"].ToString();
}
if (mrfNo == "")
{
mrfNo = prefixCharFromDropDownList + year + "000";
}
else
{
mrfNo = prefixCharFromDropDownList + (long.Parse(mrfNo.Substring(1)) + 1).ToString().PadLeft(2);
}
sdr.Close();
cmd = new SqlCommand($"INSERT INTO incMRF (MRF_NO) values ('{mrfNo}')",connUser);
cmd.ExecuteNonQuery();
connUser.Close();
//txtMRFNo.Text = prefixCharFromDropDownList + i.ToString();
return mrfNo;
}
I call this method on a console application as test.
static void Main(string[] args)
{
// send dropdown (selected char) as prefix to method
var newAId = getMRF_No("A");
var newAnotherAId = getMRF_No("A");
var newBId = getMRF_No("B");
var newAnotherAId2 = getMRF_No("A");
Console.ReadKey();
}

Retrieve Rows Value to Textboxes C# & SQL Server

Do you have any ideas on how I can put this to rows:
in this texboxes?
or sooner 10 rows to 10 textboxes?
I only know is to retrieve one row:
if (Inventory.passQty == "1")
{
SqlConnection connection = new SqlConnection("Data Source = DESKTOP-ANJELLO\\SQLEXPRESS; Initial Catalog = db_ADAPurchase; Persist Security Info = True; User Id = sa; Password = mm4;");
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Format("SELECT * FROM tbl_PurchaseRequest WHERE request_id = {0}", Inventory.passID);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
label_RID.Text = dr.GetString(0);
label_Item1.Text = dr.GetString(1);
txb_Title.Text = dr.GetString(2);
cbx_vendor.Text = dr.GetString(3);
txb_address.Text = dr.GetString(4);
label_date.Text = dr.GetString(5);
cbx_terms.Text = dr.GetString(6);
txb_ITD1.Text = dr.GetString(7);
txb_Qty1.Text = dr.GetSqlInt32(8).ToString();
label_unit1.Text = dr.GetString(9);
txb_UntP1.Text = dr.GetSqlInt32(10).ToString();
txb_TotP1.Text = dr.GetSqlInt32(11).ToString();
label_total.Text = dr.GetSqlInt32(12).ToString();
txb_reqBy.Text = dr.GetString(13);
}
connection.Close();
}
How do I make this to retrieve multiple rows in different textboxes?
Thanks for helping me!
PS: Sir #mohit-shrivastava can you please help me again?🙏
You can do something like this but GridView is instead a very good idea to implement this kind of situation.
if (Inventory.passQty == "1")
{
SqlConnection connection = new SqlConnection("Data Source = DESKTOP-ANJELLO\\SQLEXPRESS; Initial Catalog = db_ADAPurchase; Persist Security Info = True; User Id = sa; Password = mm4;");
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Format("SELECT * FROM tbl_PurchaseRequest WHERE request_id = {0}", Inventory.passID);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
label_RID.Text = dr.GetString(0);
label_Item1.Text = dr.GetString(1);
txb_Title.Text = dr.GetString(2);
cbx_vendor.Text = dr.GetString(3);
txb_address.Text = dr.GetString(4);
label_date.Text = dr.GetString(5);
cbx_terms.Text = dr.GetString(6);
label_total.Text = dr.GetSqlInt32(12).ToString();
txb_reqBy.Text = dr.GetString(13);
int number = 1;
do
{
TextBox tb = this.Controls.Find("txb_ITD" + number.ToString(), true).FirstOrDefault() as TextBox;
tb.Text = dr.GetString(7);
TextBox tb1 = this.Controls.Find("txb_Qty" + number.ToString(), true).FirstOrDefault() as TextBox;
tb1.Text = dr.GetSqlInt32(8).ToString();
TextBox tb2 = this.Controls.Find("label_unit" + number.ToString(), true).FirstOrDefault() as TextBox;
tb2.Text = dr.GetString(9);
TextBox tb3 = this.Controls.Find("txb_UntP" + number.ToString(), true).FirstOrDefault() as TextBox;
tb3.Text = dr.GetSqlInt32(10).ToString();
TextBox tb4 = this.Controls.Find("txb_TotP" + number.ToString(), true).FirstOrDefault() as TextBox;
tb4.Text = dr.GetSqlInt32(11).ToString();
number++;
//Since Query can pull more records than 10
if(number>=10)
{
break;
}
}
while(dr.Read())
}
connection.Close();
}
This code will read the SQL Data as the way you were reading it and then fill all the textboxes which are supposed to be printed once. Liek RequestID, Item, Title, Vendor etc.. then comes to the loop. Now dr already have the first record so we dont want to read the dr again otherwise it will take the next record in the record set so we used do-while instead of while. Now We are trying to find the controls from Control.ControlCollection.Find and put the extracted values to the concerning textboxes.
Note: The Code has not been tested. but it is to give you the glimpse of what has to be done to get the output as expected.
i think for creating multiple rows by creating multiple server side textbox.you neeed jquery for that. that is much easy faster and reliable:
Steps You required :
1.Create a webservice that pull all rows from the database.
2.Bind table rows by loping the data from webservice.
3.Create a webservice to insert all data to databse.

How to Display Messagebox When No Values Found on SQL

Following is a code to get values from table in sql and set it to relevant fields. However i want to know how to write if condition in below block code so if the datatable contains the USERID it will performs function below but if it didn't find the USERID it should popup a error message saying no User Found.
SqlCommand myCommand = new SqlCommand
("SELECT * From USER_TABLE WHERE USERID =" + userIdTextBox.Text, con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
nameTextBox.Text = (myReader["FIRST_NAME"].ToString());
lnameTextBox.Text = (myReader["LAST_NAME"].ToString());
posTextBox.Text = (myReader["POSITION"].ToString());
emailTextBox.Text = (myReader["E_MAIL"].ToString());
phoneTextBox.Text = (myReader["PHONE"].ToString());
usernameTextBox.Text = (myReader["USERNAME"].ToString());
userLevelTextBox.Text = (myReader["USER_LEVEL"].ToString());
string filename = (myReader["PROFILE_PICTURE"].ToString());
profilePicBox.Load(filename);
}
You need to check if(myReader.HasRows)
if(MyReader.HasRows)
{
while (myReader.Read())
{
//your code here.
}
}
else
{
// your alert.
}
if (myReader.Read()) //assuming you only ever have a single result...
{
//set form fields.
}
else
{
//message box
}
Edit based on comment from #dmitry-bychenko

using a button max 3 times before disabling it

I want to be able to use this button to search oracle three times at most and after the three attempts to disable the button and use a different search. Below is my code when the button is clicked to search first. If the catch is used three times I want to be able to disable the button.
private void btnCancelSearch_Click(object sender, EventArgs e)
{
try
{
//Connect to Database
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = conn.CreateCommand();
//Define SQL Query (Select)
strSQL = "SELECT * FROM Bookings WHERE BookingNo = '" + txtCnlBookingNo.Text + "'";
cmd.CommandText = strSQL;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
txtBookingNo.Text = dr.GetValue(0).ToString();
txtBkgSurname.Text = dr.GetValue(1).ToString();
txtBkgForename.Text = dr.GetValue(2).ToString();
txtBkgContactNo.Text = dr.GetValue(3).ToString();
txtBkgStreet.Text = dr.GetValue(4).ToString();
txtBkgTown.Text = dr.GetValue(5).ToString();
txtBkgCounty.Text = dr.GetValue(6).ToString();
txtBkgCountry.Text = dr.GetValue(7).ToString();
txtBkgEmail.Text = dr.GetValue(8).ToString();
cboBkgNoGuests.Text = dr.GetValue(9).ToString();
cboBkgPayment.Text = dr.GetValue(10).ToString();
dtpBkgCheckIn.Text = dr.GetValue(11).ToString();
dtpBkgCheckOut.Text = dr.GetValue(12).ToString();
}
catch
{
//Display confirmation message
MessageBox.Show("Not a valid Booking No");
}
Depending on your application. You can keep track of a variable called:
int ButtonClickedCount = 0;
increment this variable everytime the button is clicked. If the click count is exceeded you notify the user or disable the button.
Not sure if this is what you trying to achieve:
Declare a variable to keep track of the number of times user have clicked, then apply your logic?
int count = 0;
private void btnCancelSearch_Click(object sender, EventArgs e)
{
if(count <3){
count++;
try
{
//Connect to Database
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = conn.CreateCommand();
//Define SQL Query (Select)
strSQL = "SELECT * FROM Bookings WHERE BookingNo = '" + txtCnlBookingNo.Text + "'";
cmd.CommandText = strSQL;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
txtBookingNo.Text = dr.GetValue(0).ToString();
txtBkgSurname.Text = dr.GetValue(1).ToString();
txtBkgForename.Text = dr.GetValue(2).ToString();
txtBkgContactNo.Text = dr.GetValue(3).ToString();
txtBkgStreet.Text = dr.GetValue(4).ToString();
txtBkgTown.Text = dr.GetValue(5).ToString();
txtBkgCounty.Text = dr.GetValue(6).ToString();
txtBkgCountry.Text = dr.GetValue(7).ToString();
txtBkgEmail.Text = dr.GetValue(8).ToString();
cboBkgNoGuests.Text = dr.GetValue(9).ToString();
cboBkgPayment.Text = dr.GetValue(10).ToString();
dtpBkgCheckIn.Text = dr.GetValue(11).ToString();
dtpBkgCheckOut.Text = dr.GetValue(12).ToString();
}
catch
{
//Display confirmation message
MessageBox.Show("Not a valid Booking No");
}
}else
{
//Implement whatever search you want here
//And disable your button here
}
}

Categories

Resources