천객만래 [千客萬來] (It has an interminable succession of visitors)

Creating GridView Columns Dynamically (Part 1, 2) 소스코드



Introduction

Few months back I wrote article on how to create DataGrid programatically. The article explained how to created a DataGrid with bound columns on the fly. Many readers asked whether we can do similar thing with templated columns. This two part article explains just that. There are actually two ways to create DataGrid templated columns dynamically - using LoadTemplate method and implementing ITemplate interface. In Part - I, we will discuss how to use the first method i.e. using LoadTemplate.

What are templates anyway?

ASP.NET list controls like DataGrid, DataList and Repeater allow flexibility in changing look and feel via the use of what is called as 'Templates'. As the name suggests template is a blue print of look and feel for data displayed in certain areas of the control. For example, HeaderTemplate represents blue print of the header of the control. Similarly, ItemTemplate represents individual item or row of the DataGrid. These sectons are represented by markup like <ItemTemplate> and <HeaderTemplate>.

LoadTemplate method

If you see the class hierarchy of Page class it looks like this:
System.Object
   System.Web.UI.Control
      System.Web.UI.TemplateControl
         System.Web.UI.Page
The System.Web.UI.TemplateControl class contains a method called LoadTemplate that can be used to dynamially load temlates for templated controls. The signature of LoadTemplate is like this:
public ITemplate LoadTemplate
(string virtualPath);
The method takes virtual path of a user control file i.e. .ascx file.

Creating user control file for template markup

You should store markup of the template in .ascx file. Remember that the markup should not contain actual tags like <ItemTemplate>. Typically this file will not be having any other markup. Note that one such file represents markup for one kind of template.

Example of using LoadTemplate method

We will now develop an example in which we will create a DataGrid on the fly with a single template column. The template column simply contains a Label control but you can add any other controls as well. Our example will need to follow steps given below:
  • Create a new ASP.NET web application
  • Create a new web form
  • Create a user control file (.ascx) for template markup
  • Write code to add a DataGrid to the form
  • Load the template from the .ascxfile
  • Bind the DataGrid with some datasource
Out of above steps first two are common to any web application and we will not discuss them here. So, let us start by creating a user control file for our template.

User control file for our example

You may add a new web user control (.ascx) to your project. Add following markup to the file:
<%@ Control Language="C#" %>
<asp:label ID="label1" Runat="server" 
text='<%# Databinder.Eval
(((DataGridItem)Container).DataItem,"lastname")%>'>
</asp:label>
Note that this markup looks same as if we would have used it in design mode. Here, we are binding a label control with the lastname field from the DataMember.

Adding DataGrid to the form

Add following code to the Page_Load event of the web form
string connstr = 
@"Integrated Security=SSPI;User ID=sa;Initial 
Catalog=Northwind;Data Source=MyServer\NetSDK";
SqlConnection cnn=new SqlConnection(connstr);
SqlDataAdapter da=
new SqlDataAdapter("select * from employees", cnn);
DataSet ds=new DataSet();
da.Fill(ds, "employees");
ITemplate temp= Page.LoadTemplate("webusercontrol1.ascx");
TemplateColumn tc=new TemplateColumn();
tc.HeaderText = "Last Name";
tc.ItemTemplate = temp;
DataGrid1.Columns.Add(tc);
DataGrid1.DataSource = ds;
DataGrid1.DataMember = "employees";
DataGrid1.DataBind();
Most of the code will be familiar to you except code related to ITemplate. We have loaded our template using LoadTemplate method. We then create a TemplateColumn and set its ItemTemplate to it. Even though we have used ItemTemplate, it can be any other type of template also like EditItemTemplate. We then add this new column to the DataGrid. Note that our DataGrid instance DataGrid1 is declared at class level and hence not visible in the code shown above.

After running your application you should get a DataGrid with single templated column titled 'Last Name'.

Summary

In this article we saw how to add a templated column to a DataGrid on the fly using LoadTemplate method. This method can be used if you want to use same DataGrid with say few columns changing at run time. In the next part we will see how to create templated columns via implementing ITemplate interface. Till then keep coding!


Bipin Joshi is software consultant, trainer and author having 20+ years of experience in software development. He conducts professional courses in ASP.NET MVC, jQuery, HTML5 and Design Patterns in Thane. He is a published author and has authored or co-authored books for Apress and Wrox press. To know more about him click here. To know more about his training programs go here.

Get connected : Twitter  Facebook  Google+  LinkedIn



gridviewdyncolumns.zip



Creating GridView Columns Dynamically Part 1

http://www.binaryintellect.net/articles/331ed95f-d49f-4664-a9f7-768d6e11beb0.aspx

Creating GridView Columns Dynamically Part 2

http://www.binaryintellect.net/articles/0b4f8e1c-39e6-4070-abc0-7a970e7553bc.aspx


download source code


Posted by SB패밀리

Creating GridView Columns Dynamically (Part 2)



 

 







http://www.dotnetbips.com/articles/0b4f8e1c-39e6-4070-abc0-7a970e7553bc.aspx

Creating GridView Columns Dynamically (Part 2)

Introduction

In Part 1 you learned to create Bound Fields and Command Fields dynamically. Often your grid layout is beyond the capabilities of in-built column types and you need to use Template Fields. For example, let's say you are creating a product catalog. Certainly normal tabular layout is not suitable here as you want to display each record in a highly customized format. Template fields can come handy in such situations. In this article I am going to illustrate how template fields can be added dynamically. You will learn two techniques of doing so:

  • Using LoadTemplate() method
  • By creating a custom template class

Adding Template Fields Using LoadTemplate() Method

In order to work with this example you need to create new web site in Visual Studio. Drag and drop a GridView on the default page. Also drag and drop an SqlDataSource control. We will be setting various properties of these controls via code. In the first method of adding template fields we will be using LoadTemplate() method. The LoadTemplate() method is available to all template controls including the Page. It accepts virtual path of a file and loads the template specified therein. The return value of LoadTemplate() is an object that implements ITemplate interface.

In our example we will create the template in a User Control. To do so, add a new Web User Control to the web site and name it as ItemTemplate.ascx. Key in the following markup to it.

<%@ Control Language="C#" AutoEventWireup="true" 
CodeFile="ItemTemplate.ascx.cs" Inherits="ItemTemplate" %>
<asp:Label ID="Label1" runat="server"
Text='<%# Eval("EmployeeID") %>'>
</asp:Label>
<asp:Label ID="Label2" runat="server"
Text='<%# Eval("FirstName") %>'>
</asp:Label>
<asp:Label ID="Label3" runat="server"
Text='<%# Eval("LastName") %>'>
</asp:Label>

Notice above markup carefully. It contains three Label controls. The Text property of each Label is bound with EmployeeID, FirstName and LastName columns of Employees table respectively. The Eval() expression is one way data binding expression of ASP.NET and accepts the name of the column to bind. This user control will act as our ItemTemplate later.

Now open the code behind file of the default web form and key in the following code in Page_Load event handler.

protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource1.ConnectionString =
@"data source=.;initial catalog=northwind;integrated security=true";
SqlDataSource1.SelectCommand =
"select employeeID,FirstName,LastName from employees";
if (!IsPostBack)
{
GridView1.DataSourceID = "SqlDataSource1";
GridView1.AutoGenerateColumns = false;
TemplateField tf1 = new TemplateField();
tf1.ItemTemplate=LoadTemplate("ItemTemplate.ascx");
GridView1.Columns.Add(tf1);
}
}

The code points the ConnectionString property of SQL data source control to Northwind database. The SelectCommand property specifies a SELECT statement that fetches EmployeeID, FirstName and LastName columns of Employees table. Next, it sets DataSourceID property of GridView control to the ID of SQL Data Source control. Also, AutoGenerateColumns property is set to false as we will be adding columns programmatically. Next few lines are important. The code then creates an instance of TemplateField class. The TemplateField class represents a template column of GridView class. The ItemTemplate property of TemplateField class is then set to the return value of LoadTemplate() method. The LoadTemplate() method accepts a virtual path of the file containing template to be loaded (ItemTemplate.ascx in our case). The TemplateField is then added to the Columns collection of GridView control.

Run the web form and your browser should display something as shown below:

Notice how the template specified in the user control is applied. Also, notice that header is shown blank because we did not specified HeaderTemplate. You can either specify it or turn the header off.

Adding Template Field Using Custom Template Class

Now that you know how to use LoadTemplate() method let's move to another possibility. You learnt in the last example that LoadTemplate() method returns an object that implements ITemplate interface. You yourself can create such a class and use it directly in your code instead of using LoadTemplate() method.

To begin with add a new class named MyTemplate to App_Code folder. Key in the following code to MyTemplate class.

public class MyTemplate:ITemplate
{
    private string colname;
 public MyTemplate(string colname)
 {
        this.colname = colname;
 }
    public void InstantiateIn(Control container)
    {
        LiteralControl l = new LiteralControl();
        l.DataBinding += new EventHandler(this.OnDataBinding);
        container.Controls.Add(l);
    }
    public void OnDataBinding(object sender, EventArgs e)
    {
        LiteralControl l = (LiteralControl)sender;
        GridViewRow container = (GridViewRow)l.NamingContainer;
        l.Text = ((DataRowView)container.DataItem)[colname].ToString();
    }
}

The code creates a class called MyTemplate that implements ITemplate interface. The ITemplate interface contains a single method - InstantiateIn() - that you must implement. The code then declares a string variable to hold a column name to be displayed. The column name is set in the constructor of the class. Then InstantiateIn() method is implemented. The method receives an object of type Control that represents container or parent control. Inside we create a LiteralControl and attach an event handler (OnDataBinding) to its DataBinding event. This event is raised when the container control calls DataBind() method on itself. The LiteralControl is then added to the Controls collection of the container control.

The OnDataBinding() event handler does the job of data binding the LiteralControl with the required data. It then gets a reference to the row in which the control is being added using NamingContainer property. Finally, Text property of LiteralControl is set to the value of database column as specified in the constructor. This completes our custom template class.

Now add a new web form to the same web site. Drag and drop a GridView and SqlDataSource control as before. Add the following code in the Page_Load event handler of the form.

protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource1.ConnectionString =
@"data source=.;initial catalog= northwind;integratedsecurity=true";
SqlDataSource1.SelectCommand =
"select employeeID,FirstName,LastName from employees";
if (!IsPostBack)
{
GridView1.DataSourceID = "SqlDataSource1";
GridView1.AutoGenerateColumns = false;
TemplateField tf1 = new TemplateField();
MyTemplate t1 = new MyTemplate("FirstName");
tf1.HeaderText = "First Name";
tf1.ItemTemplate = t1;
TemplateField tf2 = new TemplateField();
MyTemplate t2 = new MyTemplate("LastName");
tf2.HeaderText = "Last Name";
tf2.ItemTemplate = t2;
GridView1.Columns.Add(tf1);
GridView1.Columns.Add(tf2);
}
}

The code sets the properties of SqlDataSource and GridView as before. Notice the code marked in bold letters. The code creates an instance of TemplateField class as before. This time the ItemTemplate property of TemplateField is set to a new instance of MyTemplate class. The column names - FirstName and LastName - are passed in the constructor. Finally, the template fields are added to the Columns collection of GridView class.

The following screen shot shows a sample run of the above web form.

That's it! Happy coding.



Posted by SB패밀리

자바스크립트로
현재 팝업창이고 팝업창을 호출한 opener 윈도우를 reload하기 위해
Opener.location.reload() 수행시 경고창 안 뜨게 하는 방법은



위와 같은 창이 안뜨게 하는 방법은

opener 윈도우에서 form 태그를 수정하면 된다.

<form id="form1" name="form1" method="get">

이렇게 하고 호출하면 경고창이 뜨는 문제는 없다.

하지만 다른 복병이 있을 수 있으니 조심하자.
Posted by SB패밀리