Populate textbox after scanning barcode - c#

Is it possible to fetch data from database after scanning the barcode? example my student ID is 201312345, after scanning my ID is it possible to populate the textboxes with my infos like name, address, course, et.? Thanks

yes thats possible!
Put the scanned student ID in a variable, make a query where you select the things you want from your database
EXAMPLE:
SqlCommand sqlSelectStudentData = new SqlCommand(SELECT * FROM tablename WHERE studentid=#studentid);
sqlSelectStudentData.Parameters.AddWithValue("#studentid", 'your scanned student id');
Put the values that return from the query in some labels or in what objects you want.
Good Luck!

string ValueOfScanner;
SqlCommand sqlcmGetStudentInfo = new SqlCommand("SELECT * FROM tablename WHERE studentid=#studentid ", connectionstring);
GetStudentInfo.Paramaters.AddWithValue("#studentid", ValueOfScanner);
SqlDataReader msGetInfo = GetStudentInfo.ExecuteReader();
DataTable dtGetInfo= new DataTable();
dtGetInfo.Load(msGetInfo);
foreach(DataRow row in dtGetInfo.Rows)
{
labelStudentName = row["studentinfo"].ToString();
labelStudentAdress = row["studentadress"].ToString();
labelStudentCourse = row["studentcourse"].ToString();
labelStudentSchool = row["studentschool"].ToString();
//And so on!
}
This is the code that should do the job. Make the query fit to your database and the tablename values to your tablenames. And put the value of what the scanner scans in the string ValueOfScanner!
Hope this helps you further

What you need to do is execute your SQL query in a TextBox TextChanged Event.
So when you scan your userId and the textbox is populated with the value, it will call a textChanged Event. This method will execute the query and get the information for the studentId from the Database that you can fill your form or whatever you have.
This is how I will do it.

Nothing special with it, the barcode scanner acts just like a keyboard and at the end of the reading it will emit an enter key so the only thing that you have to do is handle that event or whatever your logic is.

Related

How to change values of column of DataTable and show only in DataGrid not updating actual table of database

I have a column with encrypted name(all other columns are not encrypted) in SQL Database table. And I have to decrypt the column with encrypted name to show in DataGrid to users of my application but the actual table of SQL database should not be changed.(has to remain as encrypted name).
I think UpdateCommand works to update the actual table and I have to find an alternative than below UpdateCommand.
Or is there alternative way to decrypt only 1 column on DataTable which is not influencing the actual table of database?
My simple code is,
SqlCommand gridcomm = new SqlCommand();
gridcomm.Connection = Conn;
gridcomm.CommandText = "SELECT Id, customername, phonenumber FROM customers";
SqlDataAdapter gridda = new SqlDataAdapter(gridcomm);
SqlDataReader gridreader = gridcomm.ExecuteReader();
while (gridreader.Read())
{
}
gridreader.Close();
DataTable griddt = new DataTable("customers");
gridda.Fill(griddt);
foreach (DataRow row in griddt.Rows)
{
string strcustomername = (string) row["customername"].ToString();
bytecustomername = Convert.FromBase64String(strcustomername);
string decryptedcustomername = DecryptStringFromBytes_Aes(bytecustomername, byteAESKey, byteAESIV);
row["customername"] = decryptedcustomername;
}
gridda.UpdateCommand = new SqlCommandBuilder(gridda).GetUpdateCommand();
dataGrid_Totalcustomerlist.ItemsSource = griddt.DefaultView;
gridda.Update(griddt);
Hello Kay Lee: I think that if you look at implementing a Coverter in your View you will get exactly what you are looking for. In your IValueConverter implementation you can Implement the Decrypt routine. A Converter is the extended syntax in a WPF Binding Statement. If this is not clear then I will flesh out some more. Here is a great reference for Converters: http://www.wpf-tutorial.com/data-binding/value-conversion-with-ivalueconverter/
Kind Regards,
Mark Wardell
I've read many posts but there were no solution for me as this case is unusual. However, I just thought logically and finally found solution by myself.
We just need to delete 2 line of Update related code because we don't need to update.
gridda.UpdateCommand = new SqlCommandBuilder(gridda).GetUpdateCommand();
gridda.Update(griddt);
Hope this helps someone..

storing sql query results to populate dropdownlist inside formview

I have a dropdownlist of zipcodes.
It is a really large list and takes too long to load from database. So, first I was looking for the best solution to try and cache or save this data when the website is first loaded so I can use it whenever needed. I tried a list and dictionary then setting the datasource in code behind but it wouldn't let me set the selected value.
It kept telling me that it couldn't bind to a control with no datasource. To make things more difficult the dropdownlist is inside a formview.
I am just not sure the best way to go about this. I am setting the datasource and values in the formview created method but my selected value comes from the formview datasource.
private Dictionary<int, string> CreateZipcodeList()
{
string connStr = ConfigurationManager.ConnectionStrings["KlamathAlgaeEntityDevConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
Dictionary<int,string> ziplist = new Dictionary<int,string>();
//Create CoreEntity Record
SqlCommand cmd1 = new SqlCommand(#"select zipcode.ZipCodeId, zipcode.zip + ', ' + city.name + ', ' + ISNULL(GeographicState.name,'') + ', ' + Country.name as zipstring
from zipcode left outer join City on ZipCode.CityId = city.CityId
left outer join GeographicState on ZipCode.GeographicStateId = GeographicState.GeographicStateId
left outer join Country on ZipCode.CountryId = Country.CountryId
order by country.name, GeographicState.name, city.name",
conn);
try
{
conn.Open();
SqlDataReader reader = cmd1.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
if (!reader.IsDBNull(0))
{
ziplist.Add(reader.GetInt32(0), reader["zipstring"].ToString());
}
}
}
finally
{
if (conn != null)
{
conn.Close();
}
}
return ziplist;
}
protected void AddressForm_ItemCreated(Object sender, EventArgs e)
{
((DropDownList)AddressForm.FindControl("Zipcodeddl")).DataSource = CreateZipcodeList();
((DropDownList)AddressForm.FindControl("Zipcodeddl")).DataTextField = "Value";
((DropDownList)AddressForm.FindControl("Zipcodeddl")).DataValueField = "Key";
((DropDownList)AddressForm.FindControl("Zipcodeddl")).DataBind();
//((DropDownList)AddressForm.FindControl("Zipcodeddl")).SelectedValue = Eval("zipcodeid").ToString();
}
This populates the dropdown fine but when I try setting the selected value it says the control is not databound. This also doesn't store the dictionary anywhere so I need to call the function to load dictionary when ever I need it.
Ok, that is way too many records for a drop down. Why don't you allow the user to enter 5 numberic characters, and then do an search on your Database by that number. I can't think of any reason you would have to put the entire zip code list in a drop down since no one is going to manually click down to find the one they want. I don't think it servers a usefull purpose, but if there is one let me know and I will try to figure out a solution.
Thats how the post office does it.
Update
To make this work, you would have a TextBox where a user could enter the zip code they think it is. Give them a button to click to search for that zip code.
Do an sql query to your database looking for that Zipcode.Zip, and if found, bring back all the data you need.
If it is not found what I would do is start removing the last character and do another search with a modified query with "Zipcode.Zip like '%modifiedZipCode%', and bring back the closest 10 or so options, and put those in a drop down menu.
If you remove one digit and the database could not find it you could go as far as you want removing characters, and rerunning the query until you got 10 or however many records you want. At some point removing digits will become pointless because the user obviously entered an incorrect zip code.

sorting values in combobox by typing

I have a combobox that is filled with data field JobCode from database. There are 1000s of jobcode and when the user needs to select one jobcode he has to scroll down through all the jobcodes in the combobox. Can I do it in such a way that if the user types some letter of jobcode it will show the jobcodes which start with that letter in the combobox at the top of list so the user can select easily. For example, like adding some code in keypressevent in combobox.
The user must still choose from jobcodes in the list, not keep partially or incorrectly entered data that will cause wrong data entry at insert and update time.
public void jobcomboboxload()
{
OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
oleDbConnection1.Open();
OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("Select jobpk,jobcode from jobcodemastertable", oleDbConnection1);
OleDbDataReader reader = oleDbCommand1.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("jobpk", typeof(int));
dt.Columns.Add("jobcode", typeof(string));
dt.Load(reader);
cmbjobcode.ValueMember = "jobpk";
cmbjobcode.DisplayMember = "jobcode";
cmbjobcode.DataSource = dt.DefaultView;
oleDbConnection1.Close();
}
jobcode is an unique field.
Use cmbjobcode.AutoCompleteMode = AutoCompleteMode.Suggest (or other
values of the enum)
Use cmbjobcode.AutoCompleteSource = AutoCompleteSource.ListItems
Change your query including the clause ORDER BY on the field jobcode
Please, don't forget the using statement around your OleDbConnection, OleDbCommand and OleDbDataReader. This will assure the proper dispose of the before mentioned variables.
For the checking on incomplete values, you should add the Validating event and, in that event, check if the text entered is present in your strings.
The combobox has a method called FindStringExact() that can help.
Set your ComboBox AutoCompleteMode properties to Suggest AND AutoCompleteSource to ListItems or else you won't see the suggestion.
Like Steve said you can change your query and add ORDER BY on your request field to set the order in which you want them in your SELECT statement.
Hope this helps don't hesitate if you have any questions.

Getting data from MySQL connection and showing it on a TextBox

I have created a MySQL table. I can insert Data but now I'd like to get the saved data after I enter it into another tab's TextBox in my Windows Application in c# language.
I have coded the button "Refresh" to get the data, but I dont know if its correct or not. Basically I want to click it, get the data from the table, and post it at the textbox.
Here is what I got so far for the getting data part:
private void button3_Click(object sender, EventArgs e)
{
string clanname, date, type, rules, final;
string connString = "Server=localhost;Database=request;Uid=root;Pwd=;";
using (MySqlConnection mcon = new MySqlConnection(connString))
using (MySqlCommand cmd = mcon.CreateCommand())
{
mcon.Open();
cmd.CommandText = "SELECT * FROM requesttcw";
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
clanname = textBox1.Text.Trim();
date = textBox2.Text.Trim();
type = textBox2.Text.Trim();
rules = textBox2.Text.Trim();
}
}
}
}
Please help!
Thanks
The Select query in your question is fetching data from your requesttcw table. You will want to read that data from your reader instance and add it to the appropriate text boxes. For instance, you could do something like this to get data:
//textBox1 will hold the value of the first row and first column of your database.
textBox1.Text = reader.GetString(0);
Updating the index in the GetString command above will change the column from which you are fetching data. So, you will have to update that index appropriately to fetch the proper data from your table and insert to the right text box's .Text property.
I don't know what type of data you are dealing with in your table. If the type is something other than string, you will want to use the appropriate Get function for the type, whether int, double, etc. Check out the MySqlDataReader reference page for more types.
Depending on the frequency of which your table layout changes, you may also want to use .GetOrdinal to get data using your reader. This command lets you specify a column name instead of its index. The above call could be changed to:
//assuming "clanname" is a column in your database
textBox1.Text = reader.GetString(reader.GetOrdinal("clanname");
Lastly, in your example you used
while (reader.Read()) { ... }
This will loop through each row in your query result set. I don't know how many text boxes you have or if you are looking for a specific format, but be aware that if you want to show data for a field from multiple rows in your text boxes, you will have to append to the Text property for each loop iteration.

how to populate textboxes with values of datareader

i have some textboxes. in first textbox i entered a vaue like empid. after the clicking a button which goes to database and checks for the columns specified by me.
i get that data in datareader.
from datareader i need to display the particular employ information in the remaining textboxes.
how can i achieve this.
Assuming your datareader is called rdr, something like this would work:
while(rdr.Read())
{
txtBox1.Text = rdr.Item["DBFieldName1"].ToString();
txtBox2.Text = rdr.Item["DBFieldName2"].ToString();
}
while (dr.Read())
{
string checkValue = dr.GetValue(0).ToString();
if (checkValue == myEmpIdTextbox.Text)
{
Texbox2.Text = dr.GetValue(1).ToString();
Texbox3.Text = dr.GetValue(2).ToString();
}
}
Works in C# - Visual Studio 2015.
The values in the brackets () next to GetValue indicate the column number, relative to your SQL Select query.
EXAMPLE:
SELECT coloumn1, coloumn2, coloumn3 FROM table
Then, in this case, Textbox3.Text will be made equal to the data in coloumn3, and Textbox2. Text to coloumn2, for that row where coloumn1 is equal to your value in your Empid textbox.

Categories

Resources