Update gridview content on textbox_TextChanged event outside the gridview - c#

I have searched for this but could not find any solution for textchanged event outside the gridview causing changes in results. I am unable to attach image being a newbie. I want results shown in gridview through data table to update according to what I type in textbox placed outside of gridview. code in c# will be appreciated. In the end, I want to retrieve ID on pressing ENTER key to use further.
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataTable table = new DataTable();
string sql; table.Columns.Add("Name");
dbconnect db = new dbconnect();
db.createconnection();
sql = "select custcompany from customer";
db.dbadapter = new OleDbDataAdapter(sql, db.dbconnection);
DataTable dtt = new DataTable();
db.dbadapter.Fill(dtt);
for (int i = 0; i < dtt.Rows.Count; i++)
{
table.Rows.Add(dtt.Rows[i][0]);
}
sql = "select suppcompany from supplier";
db.dbadapter = new OleDbDataAdapter(sql, db.dbconnection);
DataTable dtt1 = new DataTable();
db.dbadapter.Fill(dtt1);
for (int i = 0; i < dtt1.Rows.Count; i++)
{
table.Rows.Add(dtt1.Rows[i][0]);
}
dataGridView1.DataSource = table;
if (textBox1.Text != "")
{
DataView dv = new DataView();
dv.RowFilter = string.Format("Name = '{0}'", textBox1.Text);
dataGridView1.DataSource = dv;
}
else if (textBox1.Text == "")
{
dataGridView1.DataSource = table;
}
}
table is the name of DataTable populated on Load event.

If test box has value, you are creating a new instance of DataView and assigning it to the dataGridView1, my question is is there value in DataView object? If you are doing exactly what you have given in the question then it won't work, because dv doesn't have value to show in the dataGridView1.
Get the table data on TextChanged event by accessing the database. If you have any code where you are getting the database values into the table then use it in this event before binding to the DataGridView1.
Because the table value will be lost after PostBack. So you need to reload the value into table again. Try the following,
private void textBox1_TextChanged(object sender, EventArgs e)
{
//table = fill the table with proper values by accessing the database
if (textBox1.Text != "")
{
DataView dv = table.DefaultView;
dv.RowFilter = string.Format("Name = '{0}'", textBox1.Text);
dataGridView1.DataSource = dv;
dataGridView1.DataBind();
}
else if (textBox1.Text == "")
{
dataGridView1.DataSource = table;
dataGridView1.DataBind();
}
}
Update
To search names that begins with letters use,
dv.RowFilter = string.Format("Name like '{0}%'", textBox1.Text);
To search names that contains a letters use,
dv.RowFilter = string.Format("Name like '%{0}%'", textBox1.Text);
To search names that ends with letters,
dv.RowFilter = string.Format("Name like '%{0}'", textBox1.Text);

Related

C# Windows Form - Show first value only with duplicate value in DataGridView

I'm trying to create report and it can view in DataGridView. I'm using a simple codes in viewing the values.
Here's my code when the view button is click:
belreport.DailyReport = Convert.ToDateTime(date_day_Daily.Text).ToString("yyyy-MM-dd");
DataTable table = balreport.ViewDailyRecord(belreport);
dgv_daily.DataSource = table;
Here's my code for viewing the data from the table in my database:
// START Executing to view the data
public DataTable ViewDailyRecord(BELReport belreport) {
SqlCommand cmd = new SqlCommand();
cmd.Connection = dbcon.getcon();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM table WHERE Date=#Date";
cmd.Parameters.AddWithValue("#Date",belreport.DailyReport);
SqlDataReader dr = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(dr);
return table;
}
In my table the value can be duplicate but they have unique identifier. What I'm trying to do is something like this
When there's duplicate or multiple value of the Identifier, all you can see are the First Identifier and Particulars and amount(Because the Identifier looks multiple, I want to get rid of it)
Thanks in advance
DataGridView doesn't have any built-in support to show rows in groups. For reporting purpose it's better to use reporting tools like rdlc report.
But if the result which is shown in the image is an acceptable result, you can achieve that appearance by handling CellFormatting event and setting formatted value of each cell, based on previous cell at the column:
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//I suppose the group column is column at index 0
if (e.ColumnIndex == 0 && e.RowIndex > 0)
{
if (dataGridView1[0, e.RowIndex].Value == dataGridView1[0, e.RowIndex - 1].Value)
e.Value = "";
}
}
Here is an example output:
To test it yourself:
private void Form1_Load(object sender, EventArgs e)
{
var dt = new DataTable();
dt.Columns.Add("C1", typeof(string));
dt.Columns.Add("C2", typeof(string));
dt.Rows.Add("1", "11");
dt.Rows.Add("2", "21");
dt.Rows.Add("3", "31");
dt.Rows.Add("1", "12");
dt.Rows.Add("2", "22");
dt.Rows.Add("3", "32");
dt.Rows.Add("1", "13");
dt.Rows.Add("2", "23");
this.dataGridView1.DataSource = dt;
this.dataGridView1.Sort(this.dataGridView1.Columns[0], ListSortDirection.Ascending);
foreach (DataGridViewColumn column in this.dataGridView1.Columns)
{
column.SortMode = DataGridViewColumnSortMode.NotSortable;
}
this.dataGridView1.CellFormatting += dataGridView1_CellFormatting;
}

How to edit dynamically generated datatable and datagridview?

So i have a form that looks like this:
Image Link
and I generate the datatable for the dataviewgrid in the load function:
private void loadEmpresas(){
MySqlConnection myConn = new MySqlConnection(gVariables.myConnection);
MySqlCommand command = new MySqlCommand("Select codempresa as 'Codigo', nomempresa as 'Nombre empresa' from contabilidad.empresas", myConn);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = command;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
the table in mysql looks like this:
SQL Table Image Link
so when it is running it shows this:
Now the problems that i have are that i have no idea how to modify the width of the columns, id like the entire table to cover that gray space and i want that on click it selects the entire row not just a cell. When it clicks the row i want to pupulate the rest of the textboxes but i have a problem with the click event which for testing purposes is this:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("clicked");
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
MessageBox.Show(row.Cells[0].Value.ToString() + row.Cells[1].Value.ToString());
}
else
{
MessageBox.Show("wat");
}
}
when I click it doesn't even show a messagebox sometimes, I seriously have no idea how to handle the click row event properly :C help please T_T
For updating the column widths try using DataGridViewColumn.width:
DataGridViewColumn column = dataGridView.Columns[0];
column.Width = 60;
DataGridViewColumn.Width property information.
To select the entire row you need to change the SelectionMode of the DataGrid to FullRowSelect:
this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.MultiSelect = false;
SelectionMode information.

Search in Database, output in DataGridView

I have a Database with 2 Tables. Now i want to search for Values in my Databases.
I use this GUI so the "User" can give Information to the Textbox and the searched Values should shown in my Datagridview
I use this Code:
private void TB_MSGHeadline_TextChanged(object sender, EventArgs e)
{
try
{
if (TB_MSGHeadline.Text.Equals(""))
{
}
else
{
DataView dv = new DataView(table);
dv.RowFilter = string.Format("MessageHeadline LIKE '%{0}%'", TB_MSGHeadline.Text);
dataGridView1.DataSource = dv;
}
}
catch (Exception i)
{
MessageBox.Show("" + i);
}
}
Fill the DataGridview
private void GetData(string selectCommand)
{
//Creating a new data adapter based on the specified query.
dataAdapter = new SqlDataAdapter(selectCommand, ConnectionString);
//Create a command builder to generate SQL update, insert, and
//delete commands based on selectCommand. These are used to
//update the Database.
SqlCommandBuilder CommandBuilder = new SqlCommandBuilder();
//Populate a new data table and bind it to the BindingSource
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
BindingSource1.DataSource = table;
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = BindingSource1;
GetData("SELECT * FROM Tabelle1");
}
(Found it in a video but dont work for my problem)
But i get the Error, that the row "MessageHeadline" wasnt found
So i want to know, how can i make a LIKE search for my SQL Database?

search in datagridview C# winfom

I want to put a search option in DataGridView, i.e., User types the string or int in TextBox and similar records the DataGridView should be highlighted. I tried it using KeyPress event but didn't work.
if (Char.IsLetter(e.KeyChar))
{
for (int i = 0; i < (dgemployee.Rows.Count); i++)
{
if (dgemployee.Rows[i].Cells["Employee"].Value.ToString().
StartsWith(e.KeyChar.ToString(), true,
CultureInfo.InvariantCulture))
{
dgemployee.Rows[i].Cells[0].Selected = true;
return;
}
}
Actually, I need to search the whole DataGridView, not only one column and row. So any best solution?
If your DataGridView is bound to a DataTable or a DataView, you can do this:
Create a BindingSource and make BindingSource.DataSource the Datatable or DataView that your DGV is currently using. Then set your DataGridView.DataSource to the BindingSource. Then you can use the BindingSource.Filter property to query your datasource by setting the BindingSource.Filterto your query string which will automatically filter the DGV. You can find the syntax here - it is very similar to basic SQL queries, except you can only use wild cards on the beginning and end of the string.
Use the DataView.RowFilter property.
Also take a look at DataTable.DefaultView
Take a look at this article I wrote some time back on filtering data real time.
private void txtsearchgroup_KeyUp(object sender, KeyEventArgs e) {
SqlConnection objconnection = new SqlConnection(servername and ...);
DataView Dv = new DataView();
objcommand = new SqlCommand("select name from groupitems", objconnection);
objdataadapter = new SqlDataAdapter();
objdataadapter.SelectCommand = new SqlCommand();
objdataadapter.SelectCommand = objcommand;
objdataset = new DataSet();
objconnection.Open();
objdataadapter.Fill(objdataset);
Dv.Table = objdataset.Tables[0];
Dv.RowFilter = " name LIKE '%" + txtsearchgroup.Text + "%'";
dataGridView1.DataSource = Dv;
objconnection.Close(); }
txtsearchgroup : name of textbox for search word in datagridview1 and
txtsearchgroup_KeyUp : event of keyup for search and filter word in datagridview1 and
select name from groupitems : name is field for groupitems table and
Dv.Table = objdataset.Tables[0] : zero (0) is first table in dataset

Datagrid Binding Question

I am new at this. I am trying to populate a datagrid from a table source. My code is attempting to do two things.
First it populates a dataGrid with columns from a table. Then it adds a column called "SELECT" at the end of the grid. This select is CheckBox. However, when I execute this code, it adds the "SELECT" column twice.
I want to see it once. What am I doing wrong?
private void BankFlow_Load(object sender, EventArgs e)
{
initMethod();
dataTable = getBankFlowData(globalConnection);
dataGridView1.DataSource = dataTable;
}
private static DataTable getBankFlowData(OracleConnection oc)
{
DataTable dt = new System.Data.DataTable();
try
{
OracleCommand od = oc.CreateCommand();
od.CommandText = "SELECT * FROM BANK_FLOW_SOURCE";
od.CommandType = System.Data.CommandType.Text;
OracleDataAdapter adapter = new OracleDataAdapter(od);
adapter.Fill(dt);
}
catch (Exception)
{
}
return dt;
}
private static void initMethod()
{
targetSystem = ConfigurationManager.ConnectionStrings["prototype"].ConnectionString.ToString();
Console.WriteLine("Target : {0}", targetSystem);
sourceSystem = ConfigurationManager.ConnectionStrings["qlprod8"].ConnectionString.ToString();
Console.WriteLine("Source : {0}", sourceSystem);
globalConnection.ConnectionString = sourceSystem;
globalConnection.Open();
}
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
col.HeaderText = "SELECT";
col.ReadOnly = false;
col.DefaultCellStyle.BackColor = Color.Beige;
dataGridView1.Columns.Add(col);
}
Your problem is that the databindingcomplete event happens more then you think. In fact anytime some data changes it will fire.
You need to add the column outside of the databindingcomplete event.
EDIT
Actually since you are databinding, you may want to consider adding the column to your datatable. You would do this before the binding the datatable to the grid. Essentially, just create a datacolumn named select, that has the type of boolean and then add the datacolumn to the datatable.

Categories