Saturday, October 14, 2006

Tips and Tricks on cloning data-bound controls

Here are some tips and tricks on cloning the Data-Bound controls.

Cloning DataGrid/GridView
It is common mistake when you would like to copy the assigned DataGrid's DataSource to another DataGrid's datasource like

DataGrid2.DataSource = (DataSet)DataGrid1.DataSource;

You would simply get the NullReference exception. It seems work but it doesn't. A better way is store the needed DataSet to Cache or Session and reuse it for subsequent data binding.

Object objDS = Cache["MyDS"];
if(objDS != null)
{
DataSet ds = (DataSet)objDS;
DataGrid1.DataSource = ds;
DataGrid2.DataSource = ds;
}
else
{
DataSet ds = new DataSet();
// open conn, fill the DS;
DataGrid1.DataSource = ds;
DataGrid2.DataSource = ds;

Cache["MyDS"] = ds;
}

THERE is another way cloning the content of Grid by rendering its HTML contents to HtmlTextWriter. Try to put this code in the Button's Click event.

StringBuilder strBuilder = new StringBuilder();
StringWriter writer = new StringWriter();

HtmlTextWriter textWriter = new HtmlTextWriter(writer);
strBuilder = writer.GetStringBuilder();
dgrdAuthors.RenderControl(textWriter);

string strContent = strBuilder.ToString();
Response.Write(strContent);


Once you click the button, the cloned Grid appears. This code is particularly useful especially you would like to send the content of Grid over email.


.....
objMail.Body = strContent
objMail.BodyFormat = MailFormat.Html
....



Cloning DropDownList/CheckBoxes/RadioButtonList
How do you make two DropDownLists, which bound to a datasource to have identical items? The very basic method is use of DataSet like

DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "MyText";
DropDownList1.DataValueField = "MyValue";
DropDownList1.DataBind();

DropDownList2.DataSource = ds;
DropDownList2.DataTextField = "MyText";
DropDownList2.DataValueField = "MyValue";
DropDownList2.DataBind();

It works fine. No complain. What if you use forward-only IDataReader for performance wise? You may need to have two IDataReaders for each DDL's data-binding. Here is another trick where only one DataReader is needed.

reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DropDownList1.DataSource = reader;
DropDownList1.DataTextField = "MyText";
DropDownList1.DataValueField = "MyValue";
DropDownList1.DataBind();
reader.Close();

// I am cloning the ListItemCollections of DDL1 to DDL2
DropDownList2.DataSource = DropDownList1.Items;
DropDownList2.DataTextField = "Text";
DropDownList2.DataValueField = "Value";
DropDownList2.DataBind();



Much simpler, much faster, much neat !

No comments: