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


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


Using TimeStamp columns to keep track of database record versions

2011-10-07

Timestamp is a value that is incremented by the database whenever an insert or update operation is performed.

Even though the name Timestamp could be a bit misleading, this value has no relevance to a clock related time. This only shows a linear progression of time.

For an example , it is something like your database saying it has been two update or insert commands since your last visit.

You can see this value by referring to @@DBTS  [ select @@DBTS ]

Database Timestamp Value

Database Timestamp Value



How can this be helpful at all?

Well, in simple terms, this helps to keep track of versions of records.

For an example, assume a scenario where you have to fetch a record from a table, manipulate the data and write it back.

What if the record gets changed (from another database call) after you fetched data? You will manipulate the old data and update the record without knowing somebody has updated the record in between your fetching and updating commands.

How can timestamp help?

You can add a column to your table (you can call it “Version”) and set its data type to TimeStamp. Then whenever you update or insert a record to this table, this column will record the database timestamp after that transaction.

So before writing your manipulated data, you can check if the timestamp value remains the same as what you read at the beginning of the transaction.

Following example demonstrates how timestamp can be used to monitor versions:

The Person table used for this example has a column called “Version” which is of type Timestamp.

First simply query the Version column of the table for the person called “Robert”

Timestamp before update

Timestamp before update



After an update to the same record, we will check the version (timestamp) of the same record:

Timestamp after update

Timestamp after update



As you can see, the timestamp value for the record has been automatically updated.

Note: Timestamp columns are automatically updated by the database engine so you do not have to specify value when either inserting or updating a row of a table which has a timestamp (version) column.

So to insert a record to a table with a timestamp column simply omit the timestamp column from your insert statement.

i.e. – Person table has following columns [Id, Given_Name, Family_Name, Age, Version]

Insert statement would be:

Insert into Person(Id, Given_Name, Family_Name, Age)
Values(001, "Robert", "Nox", 78);

The database will take care of the timestamp (version) column.


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

Cassian Menol Razeek


How to use (escape) single quotation mark in sql statements

06-10-2011

We all get that day when we get an exception complaining about the single quotation or apostrophe that was in our SQL statement.

The best advisable thing to do is to use stored procedures so that all data are passed as parameters. However there are situations we have to use in-line SQL statements and even there are situations where even SQL parameters cannot manage this issue.

For example, if you use the exec method in you stored procedure body to do some dynamic stuff [read more about using exec to generate dynamic queries in stored procedures here ] you will have noticed that even if you pass a string with an apostrophe to an sql parameter it will still throw an exception at you !

So the only way out is to escape this character. Once you instruct the SQL parser to escape the character it will take the apostrophe as part of the string input not part of the command.

How to?

Simply replace your apostrophe / single quotation with two apostrophes / two single quotations .

i.e.
Replace Bob’s world With Bob’s world  <- these are two single quotation characters (not one double quotation character)

This can be easily done by using the string.replace method.

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

Cassian Menol Razeek


A stored procedure that can auto-genarate SQL queries using exec method

06-10-2011

Have you ever wanted to write a flexible and dynamic stored procedure that would allow you to send the table name as a parameter?

Have you ever wanted to write a flexible and dynamic stored procedure that would allow you to send only the condition but also the column name you want to include in the where clause?

Well I did. I wanted to create a stored procedure that would take Table name, Criteria column name  and the Target criteria value as parameters and create the SQL query dynamically.

Usually, we have to write our SQL code in the stored procedure body where we cannot treat our sql statement as a string.

The way to achieve this, however, is by using the Exec method provided in SQL.

Exec (execute) allows you to execute a command or a character string that contains Transact-SQL command(s).

Without wasting more time, following is the code I used to achieve my goal:

CREATE PROCEDURE GetRowCountByStringColumn

@TableName nvarchar(50),
@CriteriaColumnName nvarchar(50),
@CriteriaValue nvarchar(150)
AS
BEGIN

EXEC('SELECT  Count(*) FROM ' + @TableName
+ ' WHERE ' + @CriteriaColumnName + ' = ''' + @CriteriaValue + '''')

END
GO

As you can see the procedure takes three arguments:

TableName
CriteriaColumnName – the name of the column that should be checked in the where clause
CriteriaValue – the value the Criteria Column Name should be checked against

The exec command creates the SQL command (at run time) and executes it.

This helped me to create many dynamic stored procedures for my current project and saved me from having to create stored procedures for each table.

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


The Structure-Conduct-Performance Model

2010-04-01

In 1930s, a group of economists developed an approach to understand relationship among a firm’s environment, behaviour and performance. This theoretical framework, since then, is known as the Structure-Conduct-Performance (S-C-P) Model.

Structure-Conduct-Performance model

 

 

 

 

 

 

 

 

 

 

 

Structure, in this model refers to the structure of the industry in which the firm is operating. According to their findings, following factors could be used by a firm to measure the industry structure it’s operating in.

  • Number of Competing Firms
  • Homogeneity of Products
  • Cost of Entry and Exit

Conduct refers to the set of strategies that the firm implement to gain competitive advantage over its rivals.

Performance in the s-c-p model has two meanings:

  1. Performance of the individual firm
  2. Performance of the economy as a whole

The Link Among Structure, Conduct and Performance

Attributes of the industry structure define the range of options and constraints a firm has to face. In highly competitive industries, firms have a very limited motion space as they are only let with a very few options too many constraints when compared to options. In such setting, both firm’s conduct and long term performance are determined by the industry structure making (in general) firms only able to gain competitive (not competitive advantage).

On the other hand, in less competitive industries, firms have the liberty of large ranges of conduct options and fewer constraints, enabling capable firms to gain competitive advantages. However, even at this type of setting, the industry structure can impact on firms critically such as deciding how long a firm can maintain its competitive advantage.

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

Cassian Menol Razeek


A Simple JavaScript To Get English Language Definition From A Dictionary

2009-05-19

English is not my first language so I use online dictionaries frequently as a part of my daily routine to clarify and learn unfamiliar words as I read through articles in the Internet.

I have been using www.ditionary.com for a long time and I had the plan to make this work easy by creating a small application to retrieve the definition with support of a web service. This morning suddenly a new idea hit me to use JavaScript to get the word in the first place and load the appropriate URL.

How Does This Work?

When a user enters a word in the www.dictionary.com interface it redirects the user to the following dynamic URL.

http://dictionary.reference.com/browse/Target-Word

Target-Word is The word we are seeking the definition for

What this JavaScript does is it retrieves the desired word from the user via a prompt, generate the appropriate URL according to the above format and open the new URL in a new window or tab so the time taken (under normal circumstance) to, load the web site, type-in the word, wait till the site redirects you, is saved. Now time is only taken for a single server request/response.

How To Set This Up?

It’s simple, just add a new favorite (for IE) or bookmark (for FireFox) in your browser and paste following code as the URL (for IE) or Location (for FireFox):

javascript:(function(){var%20word=prompt(%22Enter Word:%22);if(word!=null){window.open(%22http://dictionary.reference.com/browse/%22+word);}})();

Add bookmark dialog box in firefox

Add bookmark dialog box in firefox

 

 

 

 

 

 

 

Now, when you open the favorite/bookmark, it will ask you for the word you want to look for and open the definition in a new window/tab.

 

Sample use of the script

Sample use of the script

 

 

 

 

It’s easier to use if you add the bookmark/favorite as a button into your bookmark/links toolbar

Bookmark button

Bookmark button


This small script helps me a lot daily so I hope this would help you too!

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

Cassian Menol Razeek



D LINQ : How to Map Columns Which Auto Generate Values At the Database

2009-05-11


I have being working on a software application made on .Net and recently my client asked me to use D LINQ instead of SQL.

D LINQ has great benefits loaded! As I started working with DLINQ I started to know that preventing SQL injection is not a headache anymore and misspelled SQL queries will not trouble agian at run time because DLINQ generates all necessary SQL inside the framework!

I chose to use annotations inside the class instead of using separate xml file. Following is a part of the first class I ported to D LINQ.

</p>
_
Public Class Process
_
Public ProcessID As Integer
_
Public BusinessProcessID As String
_
Public ProcessText As String
...
...

ProcessID column is the primary key of my database table tbl_Process.

Important Point: I use database to auto-generate values for the primary key column (integer value incremented by one).

So when I run the application, It gave me this unexpected error:

Cannot insert explicit value for identity column in table ‘tbl_Process’ when IDENTITY_INSERT is set to OFF.

Basically, the IDENTITY_INSERT when using the database to auto generate value for a field but when I ran a SQL insert statement at the database end it worked fine!

After some tough time I found out the solution for this problem!

When we use an auto-generate field in a data table we have to specifically mention it in the matching field in the appropriate class.

The code to state this is:

Syntax:

IsDbGenerated:=True

This has to be added to the annotation added for the specific column like:

</p>
_
Public ProcessID As Integer

Now D LINQ can understand that the field value is auto-generated by the database!

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

Cassian Menol Razeek



The Blood Brain Barrier

2009-01-08


I wouldn’t be wrong if I say the Brain is the most vital organ in the human body. As we all know brain handles most of critical operations inside our body such as keeping and managing memories, organizing our activities, keep other organs perform, and so much more.

The Brain, as most of us already know, works by sending electric signals through complex meshes of neurons so the brain has to maintain a good environment around to keep the accuracy of this electrical signal flow.

The environment inside the brain is the brain fluid so the ingredients or components of the brain fluids are very critical to the functionalities of brain.

Any organ of the body gets the supplies it needs through blood and so does the brain. Ingredients of human blood vary depending on the situation, food, problems of other organs, etc. so it is obvious that the blood is not the same all the time.

Not like other organs, the brain has to think a lot before extracting anything from blood because if the chemical levels of brain fluid vary it directly affects the signals passed through neurons. If the brain fluid is not maintained in an optimum level, the environment will become too noisy for neurons and sending signals would become like talking in the middle of a party.

So there is this Blood-Brain Barrier (which is also referred to as BBB) which extracts the necessary ingredients such as Oxygen and Glucose and make sure nothing else is taken in.

Blood-Brain Barrier Diagram

blood-brain-barrier

Photo courtesy: Malcolm Segal


Where is Blood-Brain Barrier Located?

BBB is located at the brain blood capillaries. These capillaries are unusual in several aspects from capillaries in other organs. Those aspects are briefly described below:

  • The end-points of cells which make up the walls of these capillaries are sealed together at their edges by tight junctions which are a key component in the barrier. These junctions make sure that water soluble substances in the blood don’t pass between the edges of cells.
  • These capillaries are enclosed by flattened cells which altogether called the ‘end-feet’ which also work as a (partial and active) barrier.
  • The only way for water soluble substances in the blood is through the walls of capillaries. These walls plays the other role in the barrier because their cell membranes are made up of a lipid/protein belayed only allowing flat-soluble molecules including those of oxygen and carbon dioxide, anesthetics and alcohol to pass through the walls of capillaries.
  • In the capillary wall there are three classes of ‘efflux pumps’ which pumps various lipid-soluble molecules back in to the blood out of the brain.

However, the brain needs water soluble compounds such as Glucose for energy production and amino acids for protein synthesis so there are these Carriers in the walls of capillaries which allow those compounds to go through the wall and move waste products and unwanted molecules in the opposite direction.

The blood-brain barrier plays another key role in keeping the volume of the brain at a constant level. Since the brain is contained inside a rigid skull it is important to keep the fluid from free movement thus keeping volume of the brain static.

Problems Related to BBB

Even though BBB is made in the sole purpose of protecting the brain, it has become a barrier to medicine to access the brain. Since many medicines are water soluble, they are barricaded at the BBB. This process has made it very hard to treat brain tumors and infections such as AIDS virus.

In fact, AIDS virus uses BBB as a shield by hiding behind the BBB from body defense mechanisms.

Due to such reasons medicine has to be made as fat-soluble but then a new problem arises because then the medicine will be absorbed by most cells of the body which may be toxic.

The alternatives are making drug molecules that can ride on natural transporter proteins or use drugs that can open the Blood-Brain-Barrier.

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

Cassian Menol Razeek


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