I need to filter a gridview that retreives filtered data from a table. Therefore I bound the gridview to a dataset. Now i can't seem to find a solution to filter it further.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = new DataSet();
SqlConnection myCon = new SqlConnection(connectionstring);
SqlDataAdapter adapter = new SqlDataAdapter(cmd, myCon);
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//need to insert code here for filtering GridView1 based on TextBox1.Text
}
Thanks for the help.
Try this:
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlConnection myCon = new SqlConnection(connectionstring);
SqlDataAdapter adapter = new SqlDataAdapter(cmd, myCon);
adapter.Fill(ds);
DataView view = new DataView();
view.Table = ds.Tables[0];
view.RowFilter = "ColumnName = " + TextBox1.Text.Trim();
GridView1.DataSource = view;
GridView1.DataBind();
}
you have to refactor your code.
Here's a complete sample which handles GridView's paging, sorting(both directions) and filtering(two columns).
// store sorting across postbacks in a ViewState variable
public string SortExpression
{
get
{
if (ViewState["GridSort"]== null)
{
ViewState["GridSort"] = "Column1 ASC";
}
return ViewState["GridSort"].ToString();
}
set { ViewState["GridSort"] = value; }
}
protected void Page_load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
Here's the main method that does all (including the filter-function):
private void BindGrid()
{
try
{
var tblData = new DataTable();
var filter1 = TextBox1.Text.Trim();
var filter2 = TextBox2.Text.Trim();
using (var sqlCon = new System.Data.SqlClient.SqlConnection(connectionstring))
{
String sql = String.Empty;
var sqlCmd = new System.Data.SqlClient.SqlCommand();
if (filter1.Length != 0 && filter2.Length != 0)
{
sql = "SELECT Column1,Column2 FROM Table WHERE Column1 LIKE #Column1 AND Column2 LIKE #Column2 ORDER BY {0}";
sqlCmd.Parameters.AddWithValue("#Column1", string.Format("%{0}%", filter1));
sqlCmd.Parameters.AddWithValue("#Column2", string.Format("%{0}%", filter2));
}
else if (filter1.Length != 0)
{
sql = "SELECT Column1,Column2 FROM Table WHERE Column1 LIKE #Column1 ORDER BY {0}";
sqlCmd.Parameters.AddWithValue("#Column1", string.Format("%{0}%", filter1));
}
else if (filter2.Length != 0)
{
sql = "SELECT Column1,Column2 FROM Table WHERE Column2 LIKE #Column2 ORDER BY {0}";
sqlCmd.Parameters.AddWithValue("#Column2", string.Format("%{0}%", filter2));
}
else
{
// no filter, select all
sql = "SELECT Column1,Column2 FROM Table ORDER BY {0}";
}
sqlCmd.CommandText = string.Format(sql, this.SortExpression);
sqlCmd.Connection = sqlCon;
using (System.Data.SqlClient.SqlDataAdapter objAdapter = new System.Data.SqlClient.SqlDataAdapter(sqlCmd))
{
objAdapter.Fill(tblData);
}
}
GridView1.DataSource = tblData;
GridView1.DataBind();
}
catch (Exception)
{
// log
throw;
}
}
Paging:
private void GridView1_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
{
this.GridView1.PageIndex = e.NewPageIndex;
BindGrid();
}
Filter-Button-Click:
private void BtnFilter_Click(object sender, System.EventArgs e)
{
BindGrid();
}
Sorting:
protected void GridView1_Sorting(object sender, System.Web.UI.WebControls.GridViewSortEventArgs e)
{
string currentSortColumn = null;
string currentSortDirection = null;
currentSortColumn = this.SortExpression.Split(' ')[0];
currentSortDirection = this.SortExpression.Split(' ')[1];
if (e.SortExpression.Equals(currentSortColumn))
{
//switch sort direction
switch (currentSortDirection.ToUpper())
{
case "ASC":
this.SortExpression = currentSortColumn + " DESC";
break;
case "DESC":
this.SortExpression = currentSortColumn + " ASC";
break;
}
}
else
{
this.SortExpression = e.SortExpression + " ASC";
}
BindGrid();
}
Just converted from VB manually, so i hope there are no remaining errors.
sql = new SqlConnection(Connection.con);
adapter = new SqlDataAdapter(#"select EntryID * from Table where Name like #Name ", sql);
adapter.SelectCommand.Parameters.AddWithValue("#Name", string.Format("%{0}%", textBox1.Text));
dt = new DataTable();
adapter.Fill(dt);
dataGridView1.DataSource = dt;
Related
I have followed method from this SO post to perform search on datagridview
Below is my attempt. I would like to stop querying database with DgvSearch() method on text change, instead use RowFilter.
Within current attempt, datagridview is properly populated from LoadDataParts(), when i start typing in TxtPP_GBC2, i see only column header, no exception is thrown.
GBC column is defined as "INT".
Expected result -> TxtPP_GBC2_TextChanged() will behave same like DgvSearch()
public partial class ProgramPart : Form
{
public SqlConnection Con { get; } = new SqlConnection(#"***");
public string UserDBO;
private DataTable dataTable = new DataTable();
public ProgramPart()
{
InitializeComponent();
LoadDataParts();
}
public void LoadDataParts()
{
string sql3 = "SELECT * FROM Parts";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql3, Con);
sqlDataAdapter.Fill(dataTable);
sqlDataAdapter.Dispose();
dataGridView1n.DataSource = dataTable;
}
private void TxtPP_GBC2_TextChanged(object sender, EventArgs e)
{
//DgvSearch(); //////// DgvSearch() works perferctly
try
{
if(txtPP_GBC2.Text == "")
{
dataTable.Clear();
LoadDataParts();
dataGridView1n.Refresh();
return;
}
(dataGridView1n.DataSource as DataTable).DefaultView.RowFilter = "GBC = '" + Convert.ToInt32(txtPP_GBC2.Text) + "'";
dataGridView1n.Refresh();
}
catch(Exception s)
{
MessageBox.Show(s.ToString());
}
}
private void DgvSearch()
{
string sql3 = "SELECT * FROM Parts WHERE GBC LIKE #GBC2 AND Description LIKE #DES";
Con.Open();
SqlDataAdapter da = new SqlDataAdapter(sql3, Con);
da.SelectCommand.Parameters.AddWithValue("#GBC2", SqlDbType.Int).Value = "%" + txtPP_GBC2.Text + "%";
da.SelectCommand.Parameters.AddWithValue("#DES", SqlDbType.VarChar).Value = "%" + txtPP_Description2.Text + "%";
DataSet ds = new DataSet();
da.Fill(ds, "Parts");
da.Dispose();
dataGridView1n.DataSource = ds;
dataGridView1n.DataMember = "Parts";
Con.Close();
}
}
You can use Convert expression function to convert value of the int column to the string and compare it using such filter:
private DataTable LoadData()
{
var dt = new DataTable();
dt.Columns.Add("C1", typeof(int));
dt.Rows.Add(1);
dt.Rows.Add(11);
dt.Rows.Add(2);
dt.Rows.Add(22);
return dt;
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = LoadData();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
var filter = "";
if (!string.IsNullOrEmpty(textBox1.Text))
filter = $"Convert([C1], System.String) = '{textBox1.Text}'";
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = filter;
}
If for any reason you prefer LIKE operator, you need to change the filter to:
filter = $"Convert([C1], System.String) LIKE '%{textBox1.Text}%'";
I have a dataset which holds a table from DB already and i have to use this same dataset in a dropdown list event.
However, I have an understanding of why the dataset is null before it arrives at the catch in my program. Besides establishing the new connection again in the regionDropDownList_SelectedIndexChanged event, is there an other way to rewrite? Below is my code. Thanks a lot:)
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
regionDropDown();
}
}
DataSet mySet;
public void regionDropDown() {
// Define ADO.NET objects.
string connectionString = WebConfigurationManager.ConnectionStrings["northwindConString"].ConnectionString;
SqlConnection myConn = new SqlConnection(connectionString);
myConn.Open();
SqlCommand cmd = new SqlCommand("Select * FROM Region", myConn);
SqlDataAdapter daRegion = new SqlDataAdapter(cmd);
DataSet dsRegion = new DataSet();
daRegion.Fill(dsRegion, "Region");
mySet = dsRegion;
foreach (DataRow row in dsRegion.Tables["Region"].Rows)
{
ListItem ls = new ListItem();
ls.Text = row["RegionID"].ToString();
ls.Value = row["RegionID"].ToString();
regionDropDownList.Items.Add(ls);
}
myConn.Close();
}
public void regionDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
regionDropDown();
foreach (DataRow row in mySet.Tables["Regions"].Rows)
{
if (regionDropDownList.SelectedValue == row["RegionID"].ToString())
{
regionDescriptionLabel.Text = row["RegionDescription"].ToString();
}
}
}
catch (Exception ex) { regionDescriptionLabel.Text = "Caught!!" + ex; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
regionDropDown();
}
}
DataSet mySet; // ?
public void regionDropDown() {
// Define ADO.NET objects.
string connectionString = WebConfigurationManager.ConnectionStrings["northwindConString"].ConnectionString;
SqlConnection myConn = new SqlConnection(connectionString);
myConn.Open();
SqlCommand cmd = new SqlCommand("Select * FROM Region", myConn);
SqlDataAdapter daRegion = new SqlDataAdapter(cmd);
DataSet dsRegion = new DataSet();
daRegion.Fill(dsRegion, "Region");
mySet = dsRegion;
// If you want,custom logic then you might use this code,
// else just provide datatextfield and datavalue field before binding..
foreach (DataRow row in dsRegion.Tables["Region"].Rows)
{
ListItem ls = new ListItem();
ls.Text = row["RegionID"].ToString();
ls.Value = row["RegionID"].ToString();
regionDropDownList.Items.Add(ls);
}
myConn.Close();
}
Now in case of selectedindexchanged event ?
public void regionDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
regionDropDown();
foreach (DataRow row in mySet.Tables["Regions"].Rows)
{
if (regionDropDownList.SelectedValue == row["RegionID"].ToString())
{
regionDescriptionLabel.Text = row["RegionDescription"].ToString();
}
}
}
catch (Exception ex) { regionDescriptionLabel.Text = "Caught!!" + ex; }
}
Why calling again regionDropDown() here?
public void regionDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
regionDescriptionLabel.Text = regionDropDownList.SelectedItem.Text; // If value needed then regionDropDownList.SelectedValue
}
I am binding the gridview from sqlserver using dataset and datable on PageLoad.
public DataSet Ds
{
get
{
object temp = ViewState["Ds"];
return temp == null ? null : temp as DataSet;
}
set
{
ViewState["Ds"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gridCustAllInfoBind();
}
}
public void gridCustAllInfoBind()
{
try
{
//open the db connection if it is closed...
if (connection.State == ConnectionState.Closed)
connection.Open();
command = new SqlCommand();
command.CommandText = "Z_cust";
command.CommandType = CommandType.StoredProcedure;
command.Connection = connection;
SqlDataAdapter daAcc = new SqlDataAdapter(command);
this.Ds = new DataSet();
daAcc.Fill(Ds);
if (Ds.Tables[0].Rows.Count == 0)
{
Ds.Tables[0].Rows.Add(Ds.Tables[0].NewRow());
gridCustomer.DataSource = Ds;
gridCustomer.DataBind();
int columncount = gridCustomer.Rows[0].Cells.Count;
gridCustomer.Rows[0].Cells.Clear();
gridCustomer.Rows[0].Cells.Add(new TableCell());
gridCustomer.Rows[0].Cells[0].ColumnSpan = columncount;
gridCustomer.Rows[0].Cells[0].Text = "No Records Found";
}
else
{
//gridCustomer.DataSource = idr;
gridCustomer.DataSource = Ds;
gridCustomer.DataBind();
}
}
catch (Exception ex)
{
lblMessagePaySerach.Text= ex.Message;
}
finally //Close db Connection if it is open....
{
if (connection.State == ConnectionState.Open)
connection.Close();
}
}
Here I am filtering the dataset on demand, then bind the gridview to it.
protected void btnSearchCust_Click(object sender, EventArgs e)
{
if (ddlStatus.SelectedIndex == 0 && ddlColumns.SelectedIndex == 0)
{
var strExpr = "Status='Active'";
var dv = Ds.Tables[0].DefaultView;
dv.RowFilter = strExpr;
var newDS = new DataSet();
var newDT = dv.ToTable();
newDS.Tables.Add(newDT);
gridCustomer.DataSource = newDS;
int size = int.Parse(ddlPaging.SelectedItem.Value.ToString());
gridCustomer.PageSize = size;
gridCustomer.DataBind();
}
}
Here I am selecting dropdownlist values, then I have to show gridview records on demand.
protected void ddlPaging_SelectedIndexChanged(object sender, EventArgs e)
{
int size = int.Parse(ddlPaging.SelectedItem.Value.ToString());
gridCustomer.PageSize = size;
btnSearchCust_Click(sender, e);
}
I have a textBox and a search button that fills the first Gridview. After that a Second Button Copies the first grid rows in the second grid . After that i should be able to search again in the first grid and attach the other results to the second grid.
But i get an error. Thnx in advance.
Here is my code:
public partial class Grid: System.Web.UI.Page
{
DataTable Dt = new DataTable();
private DataTable Dt1
{
set { ViewState.Add("Dt1", value); }
get { return (DataTable)ViewState["Dt1"]; }
}
private void Fill_grid()
{
string query = "Select * from table " +
" where field1 like '" + TextBox1.Text + "' or filed2 like '" +TextBox1.Text + "'";
SqlConnection cnn = new SqlConnection(...);
SqlCommand cmm = new SqlCommand(query,cnn);
cmm.CommandType = System.Data.CommandType.Text;
SqlDataAdapter MyDataAdapter = new SqlDataAdapter(cmm);
DataSet DS = new DataSet();
cnn.Open();
MyDataAdapter.Fill(DS, "Client");
Dt1 = DS.Tables["klient"];
DataView dv = new DataView(Dt1);
GridView2.DataSource = DS.Tables["klient"].DefaultView;
GridView2.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
Fill_grid();
}
protected void Button1_Click(object sender, EventArgs e)
{
Fill_Second_Grid();
}
private void Fill_Second_Grid()
{
DataRow dr;
foreach (GridViewRow row in GridView2.Rows)
{
dr = Dt.NewRow();
dr["Email"] = row.Cells[0].Text; ;
Dt.Rows.Add(dr);
}
GridView3.DataSource = Dt;
GridView3.DataBind();
}
}
I'm new to databases. I'm trying to make a search utility to match user input string with records in database and display them.
System.Data.SqlClient.SqlConnection con;
System.Data.SqlClient.SqlDataAdapter da;
DataSet ds1;
private void Form1_Load(object sender, EventArgs e)
{
con = new System.Data.SqlClient.SqlConnection();
ds1 = new DataSet();
con.ConnectionString = "";
con.Open();
string sql = "SELECT * From tblLecturers";
da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
da.Fill(ds1, "Lecturers");
con.Close();
}
Form2 secondForm = new Form2();
private void btnFind_Click(object sender, EventArgs e)
{
this.Hide();
secondForm.Show();
string searchFor = textBox1.Text;
int results = 0;
int i;
DataRow[] returnedRows;
if (radioButton1.Checked)
{
returnedRows = ds1.Tables["Lecturers"].Select("Name like '%" + searchFor + "%'");
}
else
{
returnedRows = ds1.Tables["Lecturers"].Select("Department like '%" + searchFor + "%'");
}
results = returnedRows.Length;
if (results > 0)
{
secondForm.dataGridView1.DataSource = returnedRows;
}
else
{
MessageBox.Show("No such Record");
}
}
There's no error but it's just displaying a blank grid. returnedRows contains all the rows whose contents match the user input. I'm pretty sure this isn't though:
secondForm.dataGridView1.DataSource = returnedRows;
Tried rows.add using for loop, won't work. How do i do this?
Thanks in advance.
Call the BindMethod of gridView
if (results > 0)
{
secondForm.dataGridView1.DataSource = returnedRows;
secondForm.dataGridView1.DataBind();
}
else
{
MessageBox.Show("No such Record");
}
Ignore DataBind method, there is no method for windows GridView.
The datarow array can be added to dataset or datatable, using the dataset or datatable we can directly bind the GridView