DataGrid Dynamic Column

Source: Internet
Author: User
Tags bool tostring
datagrid| Dynamic template controls allow users to create complex user interfaces at virtually no time. asp.net there are many controls that use template technology (the DataGrid is an example). These controls work well, and typically templates can be saved as ascx files to increase reusability. Chances are, you don't know how your controls are laid out beforehand, and you need to dynamically add templates to deal with different events.

Another advantage of using templates is that they can be dynamically added to your control. In this way, you can design the template in advance and then add it to your control with a few simple lines of code.

The following article will show you how to add a dynamic ItemTemplate and EditItemTemplate to the DataGrid step-by-step. It also tells you how to get and update the user's changes to EditItemTemplate. The example will be very simple. Then, I will soon have an improved Tableeditor version on the tripleasp. This version will better explain how to use the dynamic template.


The realization of Itempalte
In order to dynamically add ItemTemplate and EditItemTemplate, we need to create 2 classes to implement the ITemplate interface (Interface). The first class is Genericitem. The main job of this class is to take the column name of the data source, create a text control (literal contral), assign a value to the text control, and finally add the text control to the parent control (where the parent control is the DataGrid).

So far it has been very smooth. Before continuing with the following discussion, let's look at the code and the steps to complete.
Using System;
Using System.Web;
Using System.Data; Using System.Web.UI;
Using System.Web.UI.WebControls;

Namespace Tripleasp.itemtemplates
{
<summary>
Summary description for Genericitem.
</summary>
public class Genericitem:itemplate
{
private string column;
private bool Validate;
Public Genericitem (String column)
{
this.column = column;
}
public void InstantiateIn (Control container)
{
Literal L = new Literal ();
L.databinding + = new EventHandler (this. Binddata);
Container. Controls.Add (l);
}

public void Binddata (object sender, EventArgs e)
{
Literal L = (Literal) sender;
DataGridItem container = (DataGridItem) L.namingcontainer;
L.text = ((DataRowView) container. DATAITEM) [column]. ToString ();

}
}
}

As you can see, the Genericitem class implements the ITemplate interface (interface). Because we are implementing interfaces, we must include InstantiateIn this method. This method is used to define the control objects that all child controls and templates belong to. In this method, we create a new literal control to hold the cell values of the DataGrid. Next, we added the DataBinding event handler function. This event handler actually puts the cell value in the Text property of the literal control when the DataGrid binds the data. Finally, add the literal control to the control's container collection. It's simple, isn't it?

Dynamic EditItemTemplate
The dynamic EditItemTemplate class Validateedititem is similar to Genericitem, but there are 3 different places.
The first difference is that we're adding a TextBox control instead of a literal control. In this case, in edit mode, the user can make any changes.
The second different place, you will find that we will explicitly name the control. This will enable us to get any data changes in the update event.
The last difference is that you will see a RequiredFieldValidator control associated with the textbox. This is optional. But it does let you know that there are things that can be done.
Here's the code for Validateedititem:
Using System;
Using System.Data;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web;

Namespace Tripleasp.itemtemplates
{
<summary>
Summary description for Validateedititem.
</summary>
public class Validateedititem:itemplate
{
private string column;
Public Validateedititem (String column)
{
this.column = column;
}

public void InstantiateIn (Control container)
{
TextBox TB = new TextBox ();
Tb. DataBinding + = new EventHandler (this. Binddata);
Container. Controls.Add (TB);
tb.id = column;

RequiredFieldValidator RFV = new RequiredFieldValidator ();
RFV. Text = "Please Answer";
RFV. ControlToValidate = tb.id;
RFV. Display = validatordisplay.dynamic;
Rfv.id = "Validate" + tb.id;
Container. Controls.Add (RFV);

}

public void Binddata (object sender, EventArgs e)
{
TextBox TB = (textbox) sender;
DataGridItem container = (DataGridItem) TB. NamingContainer;
Tb. Text = ((DataRowView) container. DATAITEM) [column]. ToString ();
}
}
}

Implementation of dynamic template
Now we have two classes that implement the Itempalte interface. Everything's ready! All we have to do now is to add them to our DataGrid.

We put together the Binddata and Dynamiccolumns two methods. The main binddata is to create SQL query statements, add columns to the DataGrid (Dynamic Columns), and then bind the datasheet to the DataGrid.

void Binddata ()
{
String sql = ' SELECT * From Publishers Where ' is ' not null ';
DATAGRID1.COLUMNS.ADD (Dynamiccolumns ("pub_id", false));
DATAGRID1.COLUMNS.ADD (Dynamiccolumns ("pub_name", true));
DATAGRID1.COLUMNS.ADD (Dynamiccolumns ("City", true));
DATAGRID1.COLUMNS.ADD (Dynamiccolumns ("state", true));
DATAGRID1.COLUMNS.ADD (Dynamiccolumns ("Country", true));
Datagrid1.datakeyfield = "pub_id";
DataGrid1.DataSource = getdatatable (sql);
Datagrid1.databind ();
}

Dynamiccolumns has two parameters: column (character type) and Iseditable (Boolean type). Column variables are, of course, the names of the columns we want to add to the TemplateColumn. The iseditable variable is used as a test if we want the column to be allowed for editing.
Protected TemplateColumn dynamiccolumns (string column, bool iseditable)
{
TemplateColumn genericcolumn = new TemplateColumn ();
Genericcolumn. HeaderText = column;
Genericcolumn. ItemTemplate = new Genericitem (column);
if (iseditable)
{
Genericcolumn. EditItemTemplate = new Validateedititem (column);
}
return genericcolumn;
}

As you can see, first we instantiate a TemplateColumn (Genericcolumn), and set the HeaderText attribute based on the name of the column we want to add (of course, you could set it to anything). Next, we add the ItemTemplate to Genericcolumn by adding a new Genericitem reference (reference) and passing in the name. Finally, we have to check iseditable to see if we need to be allowed to edit this column. If true, we will add a new reference to Validateedititem and pass the name of the column.


DataGrid Event
Our editing and cancellation events are very standard. You've probably seen them 100 times. In our edit event, we simply take out the number of the selected row and rebind the data.

protected void Edit_click (Object sender, DataGridCommandEventArgs e)
{
Datagrid1.edititemindex = E.item.itemindex;
Binddata ();
}
Our cancellation event is to set the current selected line number to-1. This is tantamount to telling the DataGrid that it is not in edit mode. Then we rebind the data.
protected void Cancel_click (Object sender, DataGridCommandEventArgs e)
{
Datagrid1.edititemindex =-1;
Binddata ();
}
Update events will be a little bit different from what you've seen before. However, it will remind you of your days in ASP.
protected void Update_click (Object sender, DataGridCommandEventArgs e)
{
Gets the UniqueID that's attached to the front of each textbox
Dyamically added to our DataGrid ' s edititemtempate
String uid = E.item.uniqueid + ":";

String pub_id = (string) Datagrid1.datakeys[e.item.itemindex];
String pub_name = (Request.form[uid + "pub_name"]. ToString ());
String city = (Request.form[uid + ' city ']. ToString ());
string state = (Request.form[uid + ' state ']. ToString ());
String country = (Request.form[uid + "country"]. ToString ());

Simple to update DB
UpdateRecord (Pub_id,pub_name,city,state,country);
Datagrid1.edititemindex =-1;
Binddata ();
}

In this case, the EditItemTemplate is hard-coded into the page. You may have seen some examples of how to submit data from a form, either by a value from the control's location or by a control name. However, if you are creating a control at run time, then, at the time of postback, ASP. NET is not able to get these values. To do this, we can only get these values through the Request.Form method.

When you start looking for carefully named TextBox inside the Validateedititem class, you must remember that ASP. NET has been prevented from conflicting the name of the control. In general, this includes adding the name of each DataGrid parent control, the name of the DataGrid itself, and a string representing the ordinal number of each textbox in front of the textbox's ID. We can use this method in a lot of ways. But this does not guarantee that our code is absolutely modular and reusable. Instead, we check the DataGridCommandEventArgs.Item.UniqueID and add ":" to the tail. With this UniqueID, we can safely get the edited data in the TextBox and update it to the database.


Conclusion
Dynamically adding templates to your template controls will add a little bit of work at the beginning. However, once you have set up a series of excellent template classes, you will find that the implementation of ITemplate will be very fast and easy. It runs you build powerful controls to meet the needs of your data operations. If you need a better example, look at the Tableeditor control I'm about to post in tripleasp.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.