textchanged event trigger after given seconds - c#

My requirement is that, there is a textbox and a datagrid , when i enter text in textbox by scanning, if the value is present in database it should be added to datagrid and textbox value should go empty.
i have kept this functionality in textbox textchanged event.
VALUE:
16789
35688
1678934
097544
if i scan'1678934', the value corresponding to '16789' is added in the grid and only 34 remains in textbox. how do i overcome this. should i place some timer so that once the scanning is complete the value may get added to the grid? how do i do it! or is there anyother event?
I used the following code
private void txtValue_TextChanged(object sender, EventArgs e)
{
if (txtValue.Text != "")
{
dataGridView1.Columns.Clear();
strValue = "SELECT NAME FROM EMPDETAIL WHERE ID = #input";
MySqlCommand cmdValue = new MySqlCommand(strValue, connection);
connection.Open();
cmdValue.Parameters.AddWithValue("#input", input);
MySqlDataAdapter adapterValue = new MySqlDataAdapter(cmdValue);
DataTable dtValue = new DataTable();
adapterValue.Fill(dtValue);
dataGridView1.DataSource = dtValue;
connection.Close();
}
}
EDIT:
Below Is the code to achieve the above functionality (as per #Daniel's Answer)
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (txtValue.Text != "")
{
if (e.KeyCode == Keys.Enter)
{
dataGridView1.Columns.Clear();
strValue = "SELECT NAME FROM EMPDETAIL WHERE ID = #input";
MySqlCommand cmdValue = new MySqlCommand(strValue, connection);
connection.Open();
cmdValue.Parameters.AddWithValue("#input", input);
MySqlDataAdapter adapterValue = new MySqlDataAdapter(cmdValue);
DataTable dtValue = new DataTable();
adapterValue.Fill(dtValue);
dataGridView1.DataSource = dtValue;
connection.Close();
}
}
}

The problem is of course that if product "123" exists, it'll be found when scanning product "1234". You can work around this using a timer like you suggested, but you really don't want that.
Barcode scanners (usually, and configurably) add a character after scanning, for example a newline character (\n).
Instead of looking up the record in the TextChanged event, add a default button to the form (which will be clicked by this newline interpreted as Enter key press), or use the KeyPress event to find out when the termination character is entered.

Related

Refresh datagridview from another user control

Using C# and Winform.
I read a couple of similar questions but couldn't find any great answers that could interlock with my code. So, bear with me and thank you in advance for helping me.
I have a single form that contains multiple User Controls. Inside the first user control, you can insert, update and delete records from the database. In the second User Control, there is a datagridview that is populated with all records.
The problem I have is that whenever I insert, update or delete a record inside the first user control. It won't refresh inside the datagridview when I swap to the second user control.
Beneath is the second user control that populates the datagridview
private void populate()
{
database.OpenConnection();
string query = "SELECT id, name, qoute, time, date from maintable";
SQLiteDataAdapter sda = new SQLiteDataAdapter(query, database.connection);
SQLiteCommandBuilder builder = new SQLiteCommandBuilder(sda);
var ds = new DataSet();
sda.Fill(ds);
dtgNav.DataSource = ds.Tables[0];
databas.CloseConnection();
}
private void Navigation_Load(object sender, EventArgs e)
{
populate();
dtgNav.Columns[0].HeaderText = "ID";
}
public void Refresh()
{
this.Refresh();
}
Beneath is the code for adding a record to the datagridview in the first user control
private void btnAdd_Click(object sender, EventArgs e)
{
database.OpenConnection();
string query = "INSERT INTO maintable (`id`, `name`, `qoute`, `time`,`date`) VALUES (#Id, #Name, #Qoute, #Time, #Date)";
SQLiteCommand command = new SQLiteCommand(query, database.connection);
command.Parameters.AddWithValue("#Id", tbxID.Text);
command.Parameters.AddWithValue("#Name", tbxName.Text.Trim());
command.Parameters.AddWithValue("#Qoute", tbxQoute.Text.Trim());
command.Parameters.AddWithValue("#Time", tbxTime.Text.Trim());
command.Parameters.AddWithValue("#Date", dtpDate.Value.ToString("yyyy-MM-dd"));
command.ExecuteNonQuery();
MessageBox.Show("Added new event into the database.");
database.CloseConnection();
usercontrol2.Refresh();
}
I would appreciate it if we found a way to refresh the datagridview when the button is clicked without changing the original code all too much.
You have a public void Refresh method in the second usercontrol, try modifying this.Refresh();, to say populate();. this should call your private void populate method that you called when loading which should reload the grid. Let me know if this helps.

i am getting an error at oledbdatareader saying no given value for one or more required parameters in ASP.NET

I have a webpage called blogwebsite and in that I have a textbox and search button. I am passing the value of textbox on button click to another webform called blogseacrh through session. I also have a database bound through these webforms. In this blogsearch webpage I have taken the session variable in a textbox. Using this textbox value I am writing a oledbcommand select query. I am fetching data from the database using this textbox value and want to display it on the blogsearch webpage. For this to happen I am using oledbdatareader to read the data and then write the fetched data in the textbox. But when I am running the webpage when I click on search button it gives me the error at the oledbdatareader line saying that no given value given for one or more required parameters.
I really can't understand what I am doing wrong. Can someone please give me a solution?
This is the button click event which is working perfectly
protected void btn_srch_Click(object sender, EventArgs e)
{
Session["name"] = txt_bnm.Text;
Response.Redirect("blogseacrh.aspx");
}
This is the code that needs to be executed on another webpage on button click event
protected void Page_Load(object sender, EventArgs e)
{
if (Session["name"] != null)
{
con.Open();
txt2_bnm.Text = Session["name"].ToString();
cmd = new OleDbCommand("select user from tbl_blogs where book_name='" + txt2_bnm.text + "',con); `
OleDbDataReader d = cmd.ExecuteReader();
while (d.Read())
{
user = d["user"].ToString();
Response.Write(user);
}
cmd = new OleDbCommand("select blogs from tbl_blogs where book_name='" + txt2_bnm.Text + "' ", con);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
blogs = dr["blogs"].ToString();
Response.Redirect(blogs);
}
con.Close();
}
I have also checked all the field names and table name and they are all correct as well.
Can someone please solve this error. i have an assignment to complete please.

How to set up BindingNavigator? - BindingNavigator is not working

I have a data app that uses a BindingNavigator. I have hooked up the navigator to a binding source, however it is not working. It will not add or delete rows. The binding source is: accountBindingSource. I don't understand what is wrong. I have the following code:
public partial class AccountDataGridView : Form
{
public AccountDataGridView()
{
InitializeComponent();
Setup();
}
private void AccountDataGridView_Load(object sender, EventArgs e)
{
// Change the back color of the first column. This can also be changed in the designer
accountGridView.Columns[0].DefaultCellStyle.BackColor = Color.FromArgb(192, 192, 255);
}
private void Setup()
{
// Define a global variable for the data table
Account = new DataTable(Text);
query = string.Format("SELECT * FROM {0}", Text);
// Establish a connection between the Database and the form
conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Tutoring Database.accdb;Persist Security Info=False");
conn.Open();
// Setup data table
OleDbDataAdapter accountAdapter = new OleDbDataAdapter(query, conn);
if (accountAdapter != null)
{
accountAdapter.Fill(Account);
}
accountGridView.DataSource = Account;
conn.Close();
}
private void DataErrorRaised(object sender, DataGridViewDataErrorEventArgs e)
{
// Data table error handling. This is triggered when the user attempts to input invalid data into the CurrentBalance column
MessageBox.Show("You have entered an invalid data type for the currency column. Please enter text formatted like so: '$0.00'",
"Account Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
}
private void btnSave_Click(object sender, EventArgs e)
{
// Update Access Database
try
{
adapter.SelectCommand = new OleDbCommand(query, conn);
adapter.InsertCommand = new OleDbCommand(query, conn);
adapter.DeleteCommand = new OleDbCommand(query, conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.Update(Account);
Console.WriteLine("Saved");
}
catch
{
}
}
private DataTable Account;
private string query;
private OleDbConnection conn;
private OleDbDataAdapter adapter = new OleDbDataAdapter();
private void accountGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
btnSave_Click(null, null);
}
}
In your question you assigned data to accountGridView.DataSource. So you can not expect the binding navigator work. The BindingSource is not connected to data and the BindingNavigator and DataGridView are not connected to the BindingSource.
You should perform these settings using designer or code:
Load data and assign data to DataSource property of BindingSource. (Using code)
Assign BindingSource to DataSource property of your DataGridView
Assign BindingSource to BindingSource property of the BindingNavigator.
Note
Changing query has nothing to do with binding source. The BindingSource and BindingNavigator work regardless of the adapter or anything which provides/saves data. Neither BindingSource nor BindingNavigator are not aware about where the data comes from actually and how the data will be saved.
I just solved my problem by creating a new BindingSource and setting its properties through code. To do this, simply drag a BindingSource onto the form. Name it whatever you would like. In the code part of your solution type something similar to this (in the constructor).
BindingSource.DataSource = Account;
Make sure to set your BindingNavigator's BindingSource to the BindingSource you just created. Thank you for the help, everyone!
EDIT: I don't know if this had anything to do with my solution but I also edited my queries a little bit. This code is mandatory for the project to work.
try
{
adapter.SelectCommand = new OleDbCommand(query, conn);
adapter.InsertCommand = new OleDbCommand("INSERT INTO Account (AccountNumber, LastName, FirstName, CurrentBalance) " +
"VALUES (?, ?, ?, ?)", conn);
adapter.DeleteCommand = new OleDbCommand(query, conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.Update(Account);
Console.WriteLine("Saved");
}
catch
{
}
For posterity:
BindingNavigator's buttons are lightweight controls, unlike a real Button control.
When you click any button in the BindingNavigator, the Focus is not stolen from the current Control, and thus the sequence of events that lead to the data being pushed to the underlying database is never called.
I know I had an example of a few lines of code you had to put in each of those lightweight button's Click handler, but can't find it for now.
This has always been a PITA!

How to store values before postback

I have two dropdownlists, ddlstates and ddlcitys.
The ddlstates has a list of Brazilian states that when clicked, loads the ddlcitys with the cities of that state. Until then, everything works correctly, but when clicking the save button which makes verification of completed fields or not, the ddlcitys back to the first option. How to store the information ddlcitys before the postback?
In code behind, have code that loads the ddlcitys:
protected void ddlstates_TextChanged(object sender, EventArgs e)
{
if (ddlstates.Text != "")
{
List<ListItem> cidades = new List<ListItem>();
SqlConnection conn = new SqlConnection(mytools.stringconection);
SqlDataReader dr = null;
conn.Open();
SqlCommand cmd = new SqlCommand("select ciddesc from cidades where cidestsigla = '" + ddlstates.SelectedValue.ToString() + "' order by 1 asc");
cmd.Connection = conn;
dr = cmd.ExecuteReader();
ddlcitys.Items.Clear();
while (dr.Read())
{
cidades.Add(new ListItem(dr[0].ToString()));
}
dr.Close();
conn.Close();
ddlcitys.DataTextField = "Text";
ddlcitys.DataValueField = "Value";
ddlcitys.DataSource = cidades;
ddlcitys.DataBind();
}
}
Asked long time ago, anyway may the answer help anyone.
On your page load event before bind any of your dropdownlists, make sure that not post back, then on your dropdown select change events , your dropdown values will not re bind so values will not changed.
hint : make sure that your aspx page enable view state (by default enabled) read more.
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
//this will called when your page loaded at first time, so bind your drop down values here.
} else {
//this will called on select change, don't bind your dropdown again, then values will be same (asp.net web forms viewstates will handle read more about viewstate).
}
}

How to search using a data-grid

I want to take the string from a text-box when the search button is pressed, then I want the row where that data grid is placed to be highlighted. I believe that this is possible. I don't know how this can be done. Please help me out.
string query = " SELECT * FROM suboffice where so_id like '%" + sor_id.Text + "%' ";
SqlConnection objConn = new SqlConnection(connectionString);
objConn.Open();
SqlDataAdapter subofficeTableAdapter1 =new SqlDataAdapter(query,objConn);
SqlCommandBuilder cBuilder = new SqlCommandBuilder(subofficeTableAdapter1);
DataTable dTable = new DataTable();
subofficeTableAdapter1.Fill(dTable);
dataGridView1.DataSource = dTable;
subofficeTableAdapter1.Update(dTable);
where sor is a search tab when ever i put any thing in this on run time my data grid view is updated. This program in to be made in c#
If you are using Windows Forms, here is a start. You may have to modify the code for your purposes if you are going to implement some sort of functionality such as "Find Next", "Find Previous", "Find All", etc.
The following is assuming you have a Button named SearchButton, a Textbox named SearchTextBox, and a DataGridView named MyDataGridView. The following code would be in the click event of your Search Button.
private void SearchButton_Click(object sender, EventArgs e)
{
MyDataGridView.ClearSelection(); //this will clear any currently selected cells
string searchstring = SearchTextBox.Text;
foreach (DataGridViewRow r in MyDataGridView.Rows)
foreach (DataGridViewCell c in r.Cells)
if (c.Value.ToString().Contains(searchstring))
{
r.Selected = true; //this will highlight the entire row
break; //if you want to "Select All" that are found, take this line out
}
}

Categories

Resources