How to use WHILE in ASP.NET - c#

When retrieving 5 values using LIMIT 0,5 and WHILE how to set these five values in five different ASP.NET text boxes? using the following code I am able to write as Response.Write but how to fix them in TextBox?
OdbcCommand cmd = new OdbcCommand(
"Select nickname, city, country, zipcode from awm_profiles WHERE email LIKE '%softmail.me%' LIMIT 0 , 30",
MyConnection);
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
//throw new Exception();
}
while (dr.Read())
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
string d = dr[3].ToString();
Response.Write(a);
Response.Write(b);
Response.Write(c);
Response.Write(d);
}

Use some data-driven control like GridView. Check this video: [How Do I:] Create Data-Driven Web Sites?
In your case texboxes will have values only from the last row.

Place TextBox Controls in the ASPX page and then set the value using the textbox's ID:
tb1.Text = a;

instead of Response.Write(a); put your textbox
TextBox1.Text = a;
TextBox2.Text = b; like that

Use a Data Repeater control.

or you can use like this
OdbcCommand cmd = new OdbcCommand(
"Select nickname, city, country, zipcode from awm_profiles WHERE email LIKE '%softmail.me%' LIMIT 0 , 30",
MyConnection);
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
//throw new Exception();
}
StringBuilder builder = new StringBuilder();
while (dr.Read())
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
string d = dr[3].ToString();
builder.AppendLine(a);
builder.AppendLine(b);
builder.AppendLine(c);
builder.AppendLine(d);
}
Response.Write(bulder.ToString());
Hope this will help :)

Related

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();
}

Select multiple values with same ID

Hi i am not sure how to retrieve all values with same id and display them in one label.
Example :
id food
1 chicken
1 fish
Desired output:
chicken,fish
How can i do that?
SqlConnection con1 = new SqlConnection(strConnString);
con.Open();
str = "select food from foodName where id= 1";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
Label1.Text = reader["food"].ToString();
}
con.Close();
Label1.Text = string.Empty;
SqlConnection con1 = new SqlConnection(strConnString);
con.Open();
str = "select food from foodName where id= 1";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
Label1.Text += reader["food"].ToString();
}
con.Close();
You can just do a foreach and add form a string using StringBuilder,
StringBuilder test = new StringBuilder();
foreach(yourClassname test in yourList)
{
test.Append(test.name);
}
Use lambda expression in C#.
var list = new List<Product>(){
new Product {ID=1, FoodName ="chicken"},
new Product{ID=2, FoodName="egg"},
new Product{ID=1, FoodName="fish"}
};
var output = list.Where(s => s.ID == 1).Select(s=>s.FoodName).ToArray(); //result will be array of items.
Use string.Join to get output results "chicken,fish"
string.Join(",", output); //result will be chicken,fish
Since you can't provide us your code. I'm assuming you have a list of food [List<Food>] and you have an id and foodName inside of it. What you can do is this:
IEnumerable<string> selectedFood = foods.FindAll(food => food.id == 1).Select(food => food.foodName);
string result = string.Join(", ", selectedFood);
You can now use the result as your label's value.
Hope this helps!
If you need to concatenate all values:
String chickenVar = "Chicken";
String fishVar = "Fish";
String result = chickenVar +", " + fishVar;

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.

database values in textbox

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 :-)

Auto increment ID with string

I'm using Access 2000-2003 database for C#. I like to have my TypeID to have a unique id as CHHTP001, CHHTP002 and etc, and display the id in TextBox before inserting new value in the database.
public void generateRateID()
{
string id;
con.Open();
string rate = "SELECT MAX(TypeID) FROM tblRoomTypeRate";
cmd = new OleDbCommand(rate, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
id = dr[0].ToString();
id = id + 1;
txtRateID.Text = "CHHRT" + id.PadLeft(3, '0');
}
con.Close();
}
The display in TextBox is CHHTP001 at first, then CHHTPCHHTP0011. How can I make the CHHTPCHHTP0011 to CHHTP002 and so on?
Use Regex. This should works as you want:
id = dr[0].ToString();//CHHTP001 Or CHHTP111
id = Regex.Replace(id, "\\d+", m => (int.Parse(m.Value) + 1).ToString(new string('0', m.Value.Length)));
txtRateID.Text = id;//CHHTP002 Or CHHTP112
Here is some general guidelines.
You should create an int variable that records what should be the number. That way you can manage your id easily. When you want to increment your id, just increment the variable.
When you want to convert the id to a string, first call ToString and PadLeft. Next you just concatenate the string to "CHHTP"! Isn't that easy?
Try this:
{
string id;
string literal; // "CHHRT" or whatever;
int sequence;
con.Open();
string rate = "SELECT MAX(TypeID) FROM tblRoomTypeRate";
cmd = new OleDbCommand(rate, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
id = dr[0].ToString();
sequence = int.Parse( new string( id.Where( char.IsDigit ).ToArray() ) );
literal = new string( id.Where( char.IsLetter ).ToArray() );
id = literal + ( sequence + 1 ).ToString( "000" );
txtRateID.Text = id;
}
con.Close();
}

Categories

Resources