I am trying to filter my datagridview by searching a keyword in a textbox from its combobox item where the source is the column name from my table. I don't have any idea how to do it in c#.
All I know is this vb.net code:
Private Sub txtkeyword_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtkeyword.TextChanged
Dim qry As String
If cmbfilter.Text = "EMPLOYEE_ID" Then
qry = "select * from tblpayslip where EMPLOYEE_ID like '%" & txtkeyword.Text & "%'"
Else
qry = "select * from tblemployee"
End If
connect()
conn.Open()
cmd = conn.CreateCommand
cmd.CommandText = qry
dr = cmd.ExecuteReader
If dr.HasRows Then
Dim dtpayslip As New DataTable
dtpayslip.Load(dr)
dgvpayslip.DataSource = dtpayslip
End If
dgvpayslip.Columns(0).HeaderCell.Value = "EMPLOYEE_ID"
dgvpayslip.Columns(1).HeaderCell.Value = "SALARY_PER_DAY"
dgvpayslip.Columns(2).HeaderCell.Value = "NO_OF_DAYS_WORKED"
dgvpayslip.Columns(3).HeaderCell.Value = "GROSS_PAY"
dgvpayslip.Columns(4).HeaderCell.Value = "SSS"
dgvpayslip.Columns(5).HeaderCell.Value = "PAG_IBIG"
dgvpayslip.Columns(6).HeaderCell.Value = "TAX"
dgvpayslip.Columns(7).HeaderCell.Value = "NET_PAY"
dgvpayslip.ClearSelection()
End Sub
You don't always need to go for SQL which will lack in performance, possibly you can fill datatable on form_load event and set rowfilter on textchange() event.
Follow the below piece of code on textchange event and move your SQL functionalities to form_load event
if (!string.IsNullOrEmpty(comboBox1.Text))
{
var dt = (DataTable)dgvpayslip.DataSource;
dt.DefaultView.RowFilter = string.Format("{0} like '%{1}%'",comboBox1.Text.Trim().Replace("'", "''"), txtkeyword.Text.Trim().Replace("'", "''"));
dgvpayslip.Refresh();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.