C#.NET

How to use LIKE operator in Dataview.RowFilter for Date Time or Numaric Fields using CONVERT

2012-01-16

The RowFilter property of the DataView allows to use flexible string similar to SQL or LINQ to easily filter rows wihtout having to iterate through them.

I had to implement a fully flexible search module for a project I’m working on. The user had to be able to perform a string search on any field displayed on the gridview. The above mentioned RowFilter method is really handy to provide such a functionality due to increased efficiency.

Assume following example:

The data table (in the database)

Field Name         Data Type  

Name                String

DateOfBirth        DateTime

Data

Name                     DOB

John                      1976-10-12

Sophie                   1990-12-30

If you want to use the RowFilter to enable flexible searching (i.e. if the user type “j” in the search textbox the search grid view would only show the record for John) you can use following code:

string SearchFor = SearchTextBox.Text;
((DataView)SearchGrid.DataContext).RowFilter = string.Concat("Name LIKE '%", SearchFor, "%'");

This will allow the above explained behaviour so if the user now enter “h” in the textbox it will show both records because both John and Sophie have the letter “h” in their names.

So what if we repeat the same and use the following code for the date of birth field?

// WRONG CODE
string SearchFor = SearchTextBox.Text;
((DataView)SearchGrid.DataContext).RowFilter = string.Concat("DateOfBirth LIKE '%", SearchFor, "%'");

We would expect the program to filter records similarly. However, if you enter “1990″ in the search textbox hoping it would filter Sophie, it would give you an error instead!

This is because the LIKE operator cannot work with non-charactor types.

The Solution!

We have to use a converter to convert the datetime field into a string just before the RowFilter is applied.

Here’s the code:

string SearchFor = SearchTextBox.Text;
((DataView)SearchGrid.DataContext).RowFilter = string.Concat("CONVERT(DateOfBirth, System.String) LIKE '%", SearchFor, "%'");

The Convert function will cast the datetime value into string just before the LIKE operation takes place. And since the datetime value is only temperory converted, the original data are not affected as well.

So if you add this code to the previously worked code for the Name column as described below:

string SearchFor = SearchTextBox.Text;
((DataView)SearchGrid.DataContext).RowFilter = string.Concat("Name LIKE '%", SearchFor, "%'");
((DataView)SearchGrid.DataContext).RowFilter = string.Concat("CONVERT(DateOfBirth, System.String) LIKE '%", SearchFor, "%'");

The Result

Now if you type “John” the grid will only show records that match that value and if you type a digit (e.g. 30) it will show the record that has 30 in the dob field (i.e. the record for Sophie)

Note
You can use the same method for any other field type which doesn’t support use of LIKE directly.

Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek


How to auto save the data table in memory into database?

2010-04-01

We frequently get to fetch data from the database, update them and then write them back to the database.

Most of the time we only have to write them back as individual records.

How about updating a whole database table in the memory and having to synchronize all changes to the actual data table?

My initial thought was this would be full of complex coding. However, thanks to Microsoft, there’s nothing much to be done at all.

So how are we gonna do this is…

We will use a data adaptor to fill our data table as usual.

The only new thing is the use of a Command Binder.

Command Binder: A command binder is capable to detect changes that have occurred to a table (in the memory) and then automatically generate appropriate SQL statements to save those changes into the actual data table (in the database).

Following is a simple example: Scenario: In my application I had to take a database table name and present data in a data grid and then save all changes made by the user.

What we need: a data table an adaptor a connection a command builder I have defined them at the form level so I can use them across the form from different events.

private DataTable _tbl;

private SqlDataAdapter _adptr;

private SqlConnection _conn;

private SqlCommandBuilder _cbldr;

Step1: Initialize connection and retrieve data from the database

_tbl = new DataTable();
_conn = FetchData.GetOpenConnection();
_adptr = new SqlDataAdapter("Select * from " + DatabaseTableName, _conn);
_cbldr = new SqlCommandBuilder(_adptr);
_adptr.Fill(_tbl);

Step2: Let the user to change data (in here simply bind the table to a grid)

dgMainGrid.DataSource = _tbl;

Step3: Save (synchronize) changes to the actual database table Even though this is a complex process and undoubtedly would take a lot of effort to do manually, Thanks to .net framework all we need is a line of code.

_adptr.Update(_tbl);

Once you call the adaptor to update the table, it will use the command builder attached to it to generate all necessary SQL command building. The database table is now up-to-date!

Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek


C# ASP.NET – GridView : How to Use Checkbox in Gridview to Select Multiple Rows

2009-01-06

I wanted to select multiple rows of the grid view using check boxes to select each row.

In this post I will discus how and what I did to achieve this goal…

I used a template column which holds a check box to select or de-select a row in the grid view.

Adding a Template Column:

There are several simple ways to add a template column/field to your grid view:

  1. Select your grid view and then click on the small task button (the small square button located to the top right corner of the grid view control) and select “Add New Column…” from the “GridView Tasks” box.
    1. Use “TemplateField” as the field type
    2. Provide a header text
    3. click ok
  2. Or… Select “Edit Columns…” from the “GridView Tasks” box and
    1. Select “TemplateField” from the “Available fields: ” section
    2. Click “Add” button
    3. Provide a header text in the “TemplateField properties: ” section
    4. click ok
  3. Or… Select “Columns” from the grid view properties and follow the steps described in the earlier method (2nd one)

Adding a Checkbox to the Template Column:

  1. Select “Edit Templates” from the “GridView Tasks” box. Then it will show you the inside of the template.
  2. Select “Item Template” from the “Display: ” drop down list.
  3. Drag and drop a check box in the item template area.
  4. Give an id as “chkid” for the check box – You can use a different name if you want but make sure you don’t confuse when I use this name in later parts of this article.
  5. Click “End Template Editing” from the “GridView Tasks” box.

If you have completed the above steps correctly, you should see the expected checkbox column added in to the grid view.

Design View
As you can see in the image above, in my example I use a Name column along with the check box column to make this clearer.

How to Databind the Template Field:

I use a datatable to populate the gridview so we have to databind our two columns.

The second column name is a “BoundField” so to databind it simply specify the name of the data table column you want to bind to this column in “DataField” property under “Data” property set in the fields dialog box you get when adding the second column (use one of the ways I described above to add a column).

Databinding the template field is a bit tricky, but not hard.

  1. Click “Edit Templates” from the “GridView Tasks” box so that you will see the check box.
  2. Click on the small button with a triangle in the upper right corner of the check box which is similar to the one we clicked on the grid view to get the “Checkbox Tasks” box and then click on the “Edit Databindings…” link inside that box.

You can use this dialog box to bind any property of the control to a data source column

In this example we will bind the “Checked” property of our check box to a Boolean column called “Selected” of the data source.

For that:

  • Select “Checked” from the Bindable Properties section and enter following in the Custom Binding section:
    • DataBinder.Eval(Container, “DataItem.Selected“)
  • Note: the word “Selected” (in red color) refers to the “Selected” field of the data source.

Populating the GridView:

As I described earlier I create a simple data table in the page load, populate it with some dummy data and then bind the grid view with it.

Note: I have used several methods to add data to a table to illustrate those to you.

The Code:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Selected", System.Type.GetType("System.Boolean")));
dt.Columns.Add(new DataColumn("Name", System.Type.GetType("System.String")));

DataRow dr = dt.NewRow();
dr.ItemArray = new object[] { false, "Cassian" };
dt.Rows.Add(dr);
dt.Rows.Add(new object[] { false, "Menol" });
dt.Rows.Add(new object[] { false, "Razeek" });

this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
}

There are several things that I’d like to bring to your notice:

  • I have checked for postback to make sure this data population is not occurred in general post backs. The reason is the framework refreshes when the grid view is re-bound.
  • So if we don’t do this check, whenever we click on a check box, a postback occurs, the grid gets refreshed, the check boxes get cleared, we cannot keep track of what check boxes are selected…!
  • As illustrate in my code, you can either first populate a datarow and then add it to the datatable
  • Or you can directly add the items using only one line of code.

Retrieving the Status of Checkboxes:

Now we have completed the interface and the user now can select several rows of the grid view using the appropriate check box.

The next step is to capture the rows that the user has selected.

In my example, I have used a button, once clicked; it will display the list of names of the selected people.

I will introduce the code first and then explain it to you.

protected void Button1_Click(object sender, EventArgs e)
{
ArrayList names = new ArrayList();
foreach (GridViewRow gvr in this.GridView1.Rows)
{
if (((CheckBox)gvr.FindControl("chkid")).Checked == true)
{
names.Add(gvr.Cells[1].Text);
}
}

this.Label1.Text = string.Empty;
foreach (object itm in names)
{
this.Label1.Text += " " + itm.ToString();
}
}

Note following:

  • The code iterates through each row of the grid view using a for each loop, takes the Name field from the selected rows and then adds those names into a arraylist
  • The GridViewRow refers to a single row in a grid view
  • Control Control.FindControl(string controlID) – GridViewRow class provides this method to find a specific control within a grid view row. This method becomes very handy in situations like this where we cannot directly access the control from the code because those are generated at run time
  • FindControl returns a control so you have to explicitly cast the returned control to the type of it

Screen Shot:

21

Conclusion:

We can use a template field with a checkbox to allow user to select multiple rows using checkboxes associated to each row. When the button is clicked, checkbox of each row is checked for its status and the row is selected if the user has chosen it.


Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek


ASP.NET – AutoPostBack : What is AutoPostBack and How AutoPostBack Works

2008-12-26

Today I was experimenting on a grid view where I was trying to select multiple rows of the grid view using a check box column.

I wrote some code in the CheckedChanged of checkbox but then I found that the code was not executed when the state of the checkbox is changed.

So I did a little googling and found out about this AutoPostBack property. This property defines whether the control should post back to the server each time when the user interacts with the control. Or, according to this scenario, a post back will fire when the user clicks on the check box or when the Checked property is changed.

AutoPostBack :

This value holds a boolean value (true/false)

If the property is set to true, a post back is sent immediately to the server and no post back is occurred when set to false.

The Use of AutoPostBack:

According to MSDN, for most WebControls, when AutoPostBack is false, only the events from actions that cause a net change in the state of the control are submitted to the server.

In other words some events are not queued to the server. For example no event is fired when a user selects a value from a drop down list or when user presses Enter or Tab key after entering a value to a textbox.

If you want such events to be fired then you have to enable autopostback by setting autopostback property to true.

How AutoPostBack Works :

When AutoPostBack is enabled, the .Net framework automatically injects following additional items into the generated HTML code.

  1. Two Hidden variables with name __EVENTTARGET and __EVENTARGUMENT
  2. A Java script method with name __doPostBack (eventtarget, eventargument)
  3. OnChange JavaScript event to the control

What is __EVENTTARGET :

__EVENTTARGET tells the server which control wants to fire the event so that the framework can fire the event on that control.

What is __EVENTARGUMENT :

__EVENTARGUMENT can be used to provide additional information to the server about the event.

What is __doPostBack (eventtarget, eventargument) :

Parameters sent to this method holds relevant target and event argument values and this method sets those values into __EVENTTARGET and __EVENTARGUMENT hidden variables so that the server can read those.

Then this method submits the form to the server where the appropriate event will be fired.

What is OnChange JavaScript event to the control :

Every control has a client side event called OnChange. When AutoPostBack is enabled for a control the framework sets the handler for this client side event as the __doPostBack method and will pass the name of the control as the first parameter, eventtarget.

Ex/

Following shows how the framework binds the __doPostBack method to the OnChange event.

<input type=”checkbox” onclick=“javascript:setTimeout(‘__doPostBack(‘CheckBox1′,”)‘, 0)” />

Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek

Recommended Books:


C# ASP.NET – GridView : How to Keep Modified Data of Template Fields when Paging is Enabled?

2008-12-04

Today I had to take care of a problem of a certain company (CIS) that I consult. They had a problem of keeping the values modified in a template field of a gridview when the user moves from one page of the grid to another.

Template fields allow us to add custom columns into a datagrid or gridview. For an instance, we can add a grid column which has a textbox in each cell.

When the gridview has several pages, the gridview holds only the rows that are displayed in its Rows (collection) property. So we cannot access the values in other pages using the gridview.Rows property.

Then I thought that I could access the whole collection of rows by referring to the DataSource property of the gridview. This is a good idea because even though the gridview only shows the rows on the current page for display purposes, the data source property of the gridview holds the whole collection of rows in it.

ASP.Net clears the data source of any control at post backs. This is done to optimize performance of communications. In addition, the state of each control is stored in ViewState so it is not necessary to keep the datasource between postbacks.

The problem is worse now because I could not use both datasource and the direct row collection from the gridview.

Of course we can use either cache or session to keep the datasouce.


Session["DataSource"] = dt;  // store our table in the session

Then to synchronize (update) the datasource which was stored in the session we have to:

  • Go to each row in the gridview
  • Get the matching data row from the data table
  • Update the fields of the data table row

Since we have enabled paging for the gridview, we have to do this when ever user changes the page he/she is viewing to preserve his/her modifications.

So we need to write our code in the PageIndexChanging event handler of the GridView.

In my example I have two columns of the grid view called “ID” and “Name” and the name is the only template column I have used so I am only updating that column in the stored data table.

Code:


protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
// get the datatable from the
DataTable dTable = (DataTable)Session["dataSource"];

// now we will iterate through all rows of the grid
// then get the matching row from the data table (datasource of our grid)
// and append the updated data (by the user) to the selected data row
foreach (GridViewRow grv in this.GridView1.Rows)
{
// get the matching row from the data table
DataRow dRow = dTable.Rows.Find(this.GridView1.DataKeys[grv.RowIndex].Value);

// set values of updated columns : here I have only let the user to edit "Name" column
dRow["Name"] = ((TextBox)grv.FindControl("txtName")).Text;
}

// go to the next page of the grid
this.GridView1.PageIndex = e.NewPageIndex;
this.GridView1.DataSource = (DataTable)Session["DataSource"];
this.GridView1.DataBind();

// show the whole collection of data in the second grid (used only to display)
this.GridView2.DataSource = (DataTable)Session["DataSource"];
this.GridView2.DataBind();
}

I have used a different gridview called GridView2 to show the whole data source without paging.

So don’t misunderstand the use of GridView2 in the last section of the code. It’s used only do display the whole set of data (without paging).

I cannot upload my code into this blog because it seems like zip files are not supported. If you like to take a glance of my code just add a comment so I’ll send the code to you via email.

Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek


  • Visitors Since Oct, 2008
  • Copyright © 1996-2010 I Learnt Today.... All rights reserved.
    iDream theme by Templates Next | Powered by WordPress