How to search using a data-grid - c#

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

Related

Adding multiple SQL queries to same Datagrid c# WPF

So... I have a datagrid that I want to populate with the medication details selected in the combobox. I want to add a new row with the new medication selected from the combobox each time a button is clicked. I am running the below method in a button click event.
private void FillSalesItemGrid()
{
using (SqlConnection con = new SqlConnection(conn))
{
con.Open();
if (!string.IsNullOrEmpty(comboBox_select_Item.Text.ToString()))
{
sqlBuilder.Append("SELECT * FROM Medication WHERE MedName = #medName");
cParameters.Add(new SqlParameter("#medName", comboBox_select_Item.Text.ToString()));
}
SqlCommand cmd = new SqlCommand(sqlBuilder.ToString(), con);
if (cParameters.Count != 0)
{
cmd.Parameters.AddRange(cParameters.ToArray());
}
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Medication");
da.Fill(dt);
dataGrid_saleItems.ItemsSource = dt.AsDataView();
sqlBuilder.Clear();
cParameters.Clear();
}
At the moment it displays the currently selected combobox item. It doesnt add a new "result" each time the button is clicked. I want it to work as if you were ringing up an item on a POS. Any help will be appreciated.
Instead of creating a new Datatable each time you have to create it once and then fill it up with each function call (SqlDataAdapter.Fill does exactly that).
That way you also only set the itemsource once.
Second solution would be to retrieve the current itemsource, convert it to a DataTable.
Someething like: DataTable table = (dataGrid_saleItems.ItemsSource as DataRowView).toTable()
If you continue with your code that will fill it up aswell.

Previous and next value datagridview

I've create a datagridview that show me my data. Then I should click on a row and I'd like to show a form where I can update my values.
Is it possible go to the previous/next element of the datagridview in another form? Because I'd like to create two buttons that allow me to scan the whole table and update each value.
Can you help me, please? I really don't know where to start
EDIT: This is the code to show my data
public static string StringaConnessione = "Data Source=localhost;Database=db;userid=root;password='';";
public static MySqlConnection Connessione = new MySqlConnection(StringaConnessione);
void MostraBtnClick(object sender, EventArgs e)
{
Connessione.Open();
MySqlDataAdapter SDA=new MySqlDataAdapter("SELECT * FROM Acquisti",Connessione);
DataTable DATA= new DataTable();
SDA.Fill(DATA);
dataGridView1.DataSource=DATA;
Connessione.Close();

how to check the value present in a datatable

I have populated the value for a datatable by using the value in a database. The data willl get populated into database on a button click. Can anybody tell how to check the value in the datatable which is populated.
I am using visual studio and coding in c#
The code for populating the datatable is as shown below :
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
var sql = #"select scriptname,accnum,Quantity,price from transac where transactio = 'Sell'";
var dataAdapter = new System.Data.SqlClient.SqlDataAdapter(sql, conn);
var dataTablesell = new DataTable();
dataAdapter.Fill(dataTablesell);
}
catch (System.Data.SqlClient.SqlException sqlEx)
{
Response.Write("error" + sqlEx.ToString());
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
DataTable has a very nice DebuggerVisualizer. Set a breakpoint after dataAdapter.Fill(dataTablesell); line; when the breakpoint is hit, hover cursor over dataTablesell to open a debug view and click magnifier button (O-) to open visualizer
You can iterate through rows of DataTable to get the value in each row for given columns.
foreach(DataRow row in dataTablesell.Rows)
{
Debug.WriteLine(row["scriptname"].ToString()); //use cell value where you want
Debug.WriteLine(row["accnum"].ToString()); //use cell value where you want
}
You can also bind the DataTable to DataGridView to see the rows in the DataTable. This MSDN article How to: Bind Data to the Windows Forms DataGridView Control explains how you would do that.
got the answer...
Instead of using Console.WriteLine as Adil has said, I used Response.Write, The code is
foreach (DataRow row in dataTablesell.Rows)
{
Response.Write(row["scriptname"].ToString());
Response.Write(row["accnum"].ToString());
}

textchanged event trigger after given seconds

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.

C# Database Displaying Relevant Data in Textboxes

I'm stuck with something and I'd appreciate it if anyone can assist me.
I have a simple MS Access database that's linked to my program. The first thing I did was fill a combobox with one of the fields in my database ("Product Description").
What I'd like to do is when a user selects an item in the combobox, all the other fields in the record be displayed in text boxes.
string sConnection;
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=XYZDatabase.accdb";
OleDbConnection dbConn;
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
cbxProducts.DisplayMember = "Product Description";
dbConn.Close();
I've considered using possibly SQL or a DataReader, though I'm really not sure.
This is the event where I want the textboxes to be filled. I'm literally stuck here.
private void cbxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
txtProductNumber.Text =
txtProductDescription.Text =
txtProductCategory.Text =
txtProductCost.Text =
}
I hope I haven't formatted my question wrong or anything, apologies if I have, this is my first time posting here! Dx
I wonder if your combo box is actually showing data from the DB.
In the first code block after
dbConn.Open()
and before
dbConn.Close()
you should have code like this:
SqlCommand sc = new SqlCommand("select prodid, proddesc from products", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("prodid", typeof(string));
dt.Columns.Add("proddesc", typeof(string));
dt.Load(reader);
cbxProducts.ValueMember = "prodid";
cbxProducts.DisplayMember = "proddesc";
cbxProducts.DataSource = dt;
And then in the second code block you need to fetch the selected Product ID first.
private void cbxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
string ID = comboBox1.SelectedValue.ToString();
//Based on ID make a sql query and fetch the details of that product from the DB.
//Follow the earlier code block to make DB connection and execute query.
//Then populate the data in individual text boxes by looping through the dr.
//I am leaving this deliberately for you to figure out and I am sure you can.
txtProductNumber.Text =
txtProductDescription.Text =
txtProductCategory.Text =
txtProductCost.Text =
}

Categories

Resources