Retrieve Rows Value to Textboxes C# & SQL Server - c#

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.

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

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

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
}
}

DataGridViewComboBoxColumn save SelectedText for each row in SQL

This is T-SQL for Inserting data from datagridview into SQL Table but the issue is that one of datagridview's column is DataGridViewComboBoxColumnand I need for each row save particular selected item in combobox. May I ask how it can be done?
public DataGridViewComboBoxColumn cbColumn;
conn.Open();
SqlTransaction sqlTrans = conn.BeginTransaction();
try
{
string delCmdTxt = "DELETE FROM PRONAJEM WHERE NA_CISLKU=#NA_CISLKU";
SqlCommand cmdDel = conn.CreateCommand();
cmdDel.Parameters.AddWithValue("#NA_CISLKU",VybraneCisku);
cmdDel.CommandText = delCmdTxt;
cmdDel.Transaction = sqlTrans;
cmdDel.ExecuteNonQuery();
string insert_sql = "INSERT INTO PRONAJEM(DATUM,PLODINA,CENAMJ,MNOZSTVIMJ,PRIKAZ,NA_ZUSTA,NA_CISLKU,RODNECISLO)VALUES" +
"(#DATUM,#PLODINA,#CENAMJ,#MNOZSTVIMJ,#PRIKAZ,#NA_ZUSTA,#NA_CISLKU,#RODNECISLO)";
using (SqlCommand sqlcom = conn.CreateCommand())
{
sqlcom.CommandText = insert_sql;
sqlcom.Transaction = sqlTrans;
sqlcom.Parameters.Add("#DATUM", SqlDbType.Date); //Replace with whatever the correct datatypes are
sqlcom.Parameters.Add("#PLODINA", SqlDbType.NVarChar);
sqlcom.Parameters.Add("#CENAMJ", SqlDbType.Decimal);
sqlcom.Parameters.Add("#MNOZSTVIMJ", SqlDbType.Decimal);
sqlcom.Parameters.Add("#PRIKAZ", SqlDbType.Date);
sqlcom.Parameters.Add("#NA_ZUSTA", SqlDbType.Decimal);
sqlcom.Parameters.Add("#NA_CISLKU", SqlDbType.NVarChar);
sqlcom.Parameters.Add("#RODNECISLO", SqlDbType.NVarChar);
var validRows = dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(row => row.Cells["DATUM"].Value != null);
foreach (DataGridViewRow row in validRows)
{
sqlcom.Parameters[0].Value = row.Cells["DATUM"].Value;
sqlcom.Parameters[1].Value = row.Cells["POLOZKAcb"].Value;
sqlcom.Parameters[2].Value = row.Cells["CENAMJ"].Value;
sqlcom.Parameters[3].Value = row.Cells["MNOZSTVIMJ"].Value;
sqlcom.Parameters[4].Value = row.Cells["PRIKAZ"].Value;
sqlcom.Parameters[5].Value = row.Cells["NA_ZUSTA"].Value;
sqlcom.Parameters[6].Value = VybraneCisku;
sqlcom.Parameters[7].Value = VybraneRodneCislo;
sqlcom.ExecuteNonQuery();
}
sqlcom.Dispose();
}
sqlTrans.Commit();
This is the creating of DataGridViewComboBoxColumn:
string query = "SELECT * FROM PLODINY ";
SqlCommand newcom = new SqlCommand(query, conn);
conn.Open();
SqlDataReader reader= newcom .ExecuteReader();
List<string> listPlodiny = new List<string>();
while (reader.Read())
{
listPlodiny.Add(reader.GetString(reader.GetOrdinal("PLODINA")) + "-" + Decimal.Parse(reader["CENAZAQ"].ToString()).ToString());
for (int i = 0; i <= listPlodiny.Count() - 1; i++)
{
}
}
cbColumn = new DataGridViewComboBoxColumn();
cbColumn.DataSource = listPlodiny;
cbColumn.DropDownWidth = 100;
dataGridView1.Columns.Add(cbColumn);
cbColumn.DisplayIndex = 3;
cbColumn.HeaderText = "Položka";
cbColumn.DataPropertyName = "POLOZKAcb";
Thank you all for your time
I think because you not set a .ValueMember property for DataGridViewComboBoxColumn...
You need to set
.ValueMember - set Value for Cell from DataSource's property.
This value will be referenced with Column.DataPropertyName's value.
.DisplayMember- Value of this will be used for diplay text in dropdown cell
Try next(updated for using of DataTable as DataSource in DataGridViewComboBoxColumn:
DataTable dtPlodiny;
using(SqlConnection sqlConn = new SqlConnection(conn))//conn - your connection string
{
string sqlQuery = #"SELECT ID, Description FROM PLODINY"; //better practice use only fields you need
using(SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtPlodiny);
}
}
cbColumn = new DataGridViewComboBoxColumn();
cbColumn.Name = "POLOZKAcb"
cbColumn.DataSource = dtPlodiny; //Changed with DataTable
//add next two rows
cbColumn.DisplayMember = "Description" //property from .Datasource you want to show for user
cbColumn.ValueMember = "ID" //property from .Datasource you want use as Value - reference to DataPropertyName
cbColumn.DropDownWidth = 100;
dataGridView1.Columns.Add(cbColumn);
cbColumn.DisplayIndex = 3;
cbColumn.HeaderText = "Položka";
cbColumn.DataPropertyName = "POLOZKAcb";
If your datagridview use always same columns,
then I think easally if you use a predefined columns(created/added through Designer). Then you can set a name for every column and use it in code as object:
this.MyColumnPolozka.Name...
for example...
if you donot get correct value from row.Cells(0).Value then try casting it to dropdownlist

Implement Search from database as alphabets are entered

I have written a code that searches specific string from database table.what i want to implement is search like when we search friends on facebook means it returns results matching to the input given even if it is partial
for example if i want to search ANDREW as soon as i enter single character results should start to appear if i enter "an" like
andy
andrew
and....
here is my code for textbox text changed method
table = new DataTable();
table.Columns.Add("Name");
table.Columns.Add("Type");
table.Columns.Add("Status");
table.Columns.Add("Date Created");
table.Columns.Add("Action");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = textBoxSearch.Text;
cmd.CommandText = "SELECT id,uName,uType,uStatus,uDate from users WHERE uName=#username ";
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
while (dr.Read())
{
MessageBox.Show(dr["uName"].ToString() + dr["uType"].ToString() + dr["uStatus"].ToString());
row = table.NewRow();
row["Name"] = dr["uName"].ToString();
row["Type"] = dr["uType"].ToString();
row["Status"] = dr["uStatus"].ToString();
row["Date Created"] = dr["uDate"].ToString();
// row["Action"] = new Button();
table.Rows.Add(row);
UsersView.DataSource = table;
}//End While for entering peresent amount of data
}//End If to check wether or not users exist
dr.Close();//Close Datareader
}
As you're using C#, why not go for something more LINQ-y?
Set up your LINQ Database Context file and use the following code to achieve what you're trying to (quickly typing this, sorry if there's any errors):
table = new DataTable();
table.Columns.Add("Name");
table.Columns.Add("Type");
table.Columns.Add("Status");
table.Columns.Add("Date Created");
table.Columns.Add("Action");
var db = new DbDataContext();
var users = (from u in db.users
where u.Contains(textBoxSearch.Text)
select u).ToList();
foreach(var user in users)
{
MessageBox.Show(user.uName + user.uType + user.uStatus);
row = table.NewRow();
row["Name"] = user.uName;
row["Type"] = duser.uType;
row["Status"] = user.uStatus;
row["Date Created"] = user.uDate.ToShortDateString();
table.Rows.Add(row);
}
UsersView.DataSource = table;
To call back to the database, the CommandText becomes
... WHERE uName LIKE #username + '%'
However, I wouldn't call back to the database every time: I'd use an auto complete control. There are several autocomplete controls for Winforms out there. And this SO answer too.

Categories

Resources