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
}
}
Related
I have be below code to navigate through records by selecting the next records id using the current id in lblID.text. But when I click on the next button for the first time it works and moves to the next id but the second and subsequent clicks don't work. I need help (below is the code)
protected void btnNext_Click(object sender, EventArgs e)
{
int currentrowID = Convert.ToInt32(lblID.Text);
SqlConnection con = new SqlConnection(connection);
string commandtext = "SELECT TOP 1 * FROM Outwards WHERE id > #currentrowID ORDER BY id";
SqlCommand command = new SqlCommand(commandtext, con);
command.Parameters.AddWithValue("#currentrowID", currentrowID);
con.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
lblID.Text = reader["id"].ToString();
lblPayerBankRoutNo.Text = reader["PayorBankRoutNo"].ToString();
lblAccountNumber.Text = reader["AccountNo"].ToString();
lblTransCode.Text = reader["TransCode"].ToString();
lblAmount.Text = reader["Amount"].ToString();
//showing front image
byte[] frontimagebyte = (byte[])reader["FImage"];
RadBinaryImage1.ImageUrl = "data:image;base64," + Convert.ToBase64String(frontimagebyte);
//showing front image
byte[] rearimagebyte = (byte[])reader["RImage"];
RadBinaryImage2.ImageUrl = "data:image;base64," + Convert.ToBase64String(rearimagebyte);
}
reader.Close();
con.Close();
}
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();
}
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.
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 :-)
I am using windows form to build an application using datagridview. Every data grid contains an empty row at the top and I suspect that it is the way that I am populating them but as I am coming to the end, I am reluctant to change any of my code as I am a beginner.
Is there a simple way to check if a row if empty, then set that to not visible?
The code that I am using:
private void displayInGrid_Customers(string sqlcmd)
{
customersDataGridView.Rows.Clear();
connect.Open();
command.Connection = connect;
command.CommandText = sqlcmd;
reader = command.ExecuteReader();
customersDataGridView.Rows.Add();
while (reader.Read())
{
DataGridViewRow rowadd = (DataGridViewRow)customersDataGridView.Rows[0].Clone();
rowadd.Cells[0].Value = reader["Customer_ID"].ToString();
rowadd.Cells[1].Value = reader["Forename"].ToString();
rowadd.Cells[2].Value = reader["Surname"].ToString();
rowadd.Cells[3].Value = reader["Address"].ToString();
rowadd.Cells[4].Value = reader["Town"].ToString();
rowadd.Cells[5].Value = reader["Postcode"].ToString();
rowadd.Cells[6].Value = reader["Date_Of_Birth"].ToString();
rowadd.Cells[7].Value = reader["Phone_Number"].ToString();
rowadd.Cells[8].Value = reader["Email"].ToString();
rowadd.Cells[9].Value = reader["Current_Rental"].ToString();
this.customersDataGridView.AllowUserToAddRows = false;
customersDataGridView.Rows.Add(rowadd);
}
reader.Close();
connect.Close();
}
private void button_view_all_customers_Click(object sender, EventArgs e)
{
command.CommandText = "SELECT CUSTOMERS.Customer_ID, CUSTOMERS.Forename, CUSTOMERS.Surname, CUSTOMERS.Address, "
+ "CUSTOMERS.Town, CUSTOMERS.Postcode, CUSTOMERS.Date_Of_Birth, CUSTOMERS.Phone_Number, CUSTOMERS.Email, CUSTOMERS.Current_Rental "
+ "from CUSTOMERS LEFT JOIN STOCK ON CUSTOMERS.Current_Rental = STOCK.Product_ID";
string cmd = command.CommandText;
displayInGrid_Customers(cmd);
}
You could use the IsNullOrWhiteSpace. But before that, you have to check your sql statement, why you have empty rows result.
while (reader.Read())
{
DataGridViewRow rowadd = (DataGridViewRow)customersDataGridView.Rows[0].Clone();
if (!string.IsNullOrWhiteSpace(reader["Customer_ID"].ToString()))
{
rowadd.Cells[0].Value = reader["Customer_ID"].ToString();
//Others Stuff
//...
this.customersDataGridView.AllowUserToAddRows = false;
customersDataGridView.Rows.Add(rowadd);
}
}