Friday, July 28, 2006

Highlight rows in a DataGrid

Here is another useful piece of code which can be helpful for novice programmers.

DataGrid is a very nice tool to present the data. It is quite easy and once you start using that, I am sure, anybody would enjoy using that control. We can bind a grid to a dataset in just two steps.


  1. Assign the DataSource property of the grid to a DataObject. The DataObject can be anything from a DataSet to an array.

  2. Call the DataBind() method to bind the data.


We can do further processing in the control in its ItemDataBound event.

Once you have bound the data, the ItemDataBound even can be used to do furthur processing.

In this example I present how to mark certain rows in a DataGrid based on some data. Here I use the Employees table in the Northwind database. I populate a grid with data and mark the Employees whose city is "Seattle"

The Code...

void Page_Load(object sender, EventArgs e)
{
DataGrid1.DataSource = GetData();
DataGrid1.DataBind();
}

void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item e.Item.ItemType == ListItemType.AlternatingItem)
{
if (e.Item.Cells[4].Text == "Seattle") // Cell4 Contains the City
{
e.Item.CssClass = "Hilite";
}
}
}




I have not included the code for creating the DataSet. The HTML has also not been inlcuded. It contains a DataGrid

See also
  1. Export DataGrid to Excel
  2. Showing Checkboxes in Grid
  3. Create Serial# column in Datagrid/DataList

    Wednesday, July 26, 2006

    Adding and Removing items from a ListBox

    This is a small piece of code which can help startup programmers in ASP.Net

    Paste this code in the code section.



    void cmdAdd_Click(object sender, EventArgs e)
    {
    ListItem LI = ListBox1.SelectedItem;

    if (LI != null)
    {
    ListBox2.Items.Add(LI);
    ListBox2.SelectedIndex = -1;
    ListBox1.Items.Remove(LI);
    ListBox1.SelectedIndex = -1;
    }
    }

    void cmdRemove_Click(object sender, EventArgs e)
    {
    ListItem LI = ListBox2.SelectedItem;

    if (LI != null)
    {
    ListBox1.Items.Add(LI);
    ListBox1.SelectedIndex = -1;
    ListBox2.Items.Remove(LI);
    ListBox2.SelectedIndex = -1;
    }
    }




    This example requires two listboxes named ListBox1 and ListBox2. At least one of them having some items.

    Thursday, July 20, 2006

    XML Encode & Decode

    Whenever we use XML in your application, we might be required to encode and decode the data which we are passing in the XML since the data may contain some special charecters like XML tags. The charecters '<', '>', '&' and '"' may have to be replaced. I use these methods to encode and decode XML strings.


    public string XMLEncode(string Value)
    {
    return Value.Replace ("&", "&amp;").Replace("'", "&apos;").Replace ("\"", "&quot;").Replace ("<", "&lt;").Replace(">", "&gt;");
    }

    public string XMLDecode(string Value)
    {
    return Value.Replace ("&amp;", "&").Replace("&apos;", "'").Replace("&quot;", "\"").Replace ("&lt;", "<").Replace ("&gt;", ">");
    }

    Tuesday, July 18, 2006

    Calling a Web Service by passing credentials

    Here is the method I use for calling WebServices from my .Net applications. Usually from web services, we might need to pass the credentials of the logged in user to the webService also

    public static MyWS.MyWSMethod GetMyWSMethod()
    {
    MyWS.MyWSMethod WS = new MyWS.MyWSMethod();
    WS.Url = System.Configuration.ConfigurationSettings.AppSettings["MyWSURL"];
    WS.PreAuthenticate = false;
    WS.Credentials = System.Net.CredentialCache.DefaultCredentials;
    return WS;
    }


    When PreAuthenticate = true, the WWW-authenticate header is sent with the first request if the authentication mechanism supports doing so. When PreAuthenticate = false, a request is made to the XML Web service method without initially attempting to authenticate the user. If the XML Web service allows anonymous access, then the XML Web service method is executed. If anonymous access is disallowed, a 401 HTTP return code is sent back to the client

    When PreAuthenticate property to true, the NetworkCredential stored in the Credentials property will be sent to along with the resource request.

    Monday, July 17, 2006

    Export DataGrid to Excel

    Most of the applications which are being developed now require data to be exported to various formats. With ASP.Net this has become quite simple

    private void Export2Excel(DataGrid grd)
    {
    Response.Clear();
    Response.Buffer = true;
    Response.ContentType = "application/vnd.ms-Excel";
    Response.Charset = "";
    EnableViewState = false;
    System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

    // Convert the controls to string literals
    ClearControls(grd);
    grd.RenderControl(oHtmlTextWriter);

    Response.Write(oStringWriter.ToString());
    Response.End();
    }

    private void ClearControls(Control Ctrl)
    {
    for (int i= Ctrl.Controls.Count - 1; i >= 0; i--)
    {
    ClearControls(Ctrl.Controls[i]);
    }

    if (!(Ctrl is TableCell))
    {
    if (Ctrl.GetType().GetProperty("SelectedItem") != null)
    {
    LiteralControl Lt = new LiteralControl();
    Ctrl.Parent.Controls.Add(Lt);
    try
    {
    Lt.Text = (string)Ctrl.GetType().GetProperty("SelectedItem").GetValue(Ctrl, null);
    }
    catch {}

    Ctrl.Parent.Controls.Remove(Ctrl);
    }
    else if (Ctrl.GetType().GetProperty("Text") != null)
    {
    LiteralControl Lt = new LiteralControl();
    Ctrl.Parent.Controls.Add(Lt);
    Lt.Text = (string)Ctrl.GetType().GetProperty("Text").GetValue(Ctrl, null);

    Ctrl.Parent.Controls.Remove(Ctrl);
    }
    }
    return;
    }


    Hope this post helped you. Please feel free to post your comments.

    Friday, July 14, 2006

    Send Mail - formatted using XML & XSL

    Most of the applications which we develop needs to send mails. Mails can be sent from ASP.Net using the System.Web.Mail.MailMessage class. This has been stated in an earlier post. This is an enhancement for the earlier method. We might need to format the mail before sending it out to the recepients. Various methods can be adopted for this purpose. One of the methods is to take the contents of the mail from an XSL file which can be merged with a DataXML.

    In this method, we can seperate the Data and Presentation layers so that it is easy to modify the static contents of the mail without recompiling the program. The following is the code sample for doing the same.


    private void SendMail(string DataXML, string XSLFileName, string ToEMailAddress, string CCEMailAddress, string FromEMailAddress)
    {
    string XML = GetFormattedXml(DataXML, XSLFileName);
    XmlDocument xDoc = new XmlDocument();
    xDoc.LoadXml(XML);
    System.Web.Mail.MailMessage oMail = new System.Web.Mail.MailMessage();
    oMail.To = ToEMailAddress;

    if (CCEMailAddress.Trim() != "")
    oMail.Cc = CCEMailAddress;
    oMail.From = FromEMailAddress;

    oMail.Subject = xDoc.SelectSingleNode("//subject").InnerText;
    oMail.Body = xDoc.SelectSingleNode("//messagebody").InnerXml;
    oMail.BodyEncoding = System.Text.Encoding.UTF8;
    oMail.BodyFormat = System.Web.Mail.MailFormat.Html;
    System.Web.Mail.SmtpMail.SmtpServer = MailServer;
    System.Web.Mail.SmtpMail.Send(oMail);

    xDoc = null;
    }

    private string GetFormattedXml(string XML, string XSLFileName)
    {
    System.Xml.Xsl.XslTransform xslt = new System.Xml.Xsl.XslTransform();
    xslt.Load(XSLFileName);
    System.IO.StringWriter stringWriter = new System.IO.StringWriter();
    XmlDocument xDoc = new XmlDocument();
    xDoc.LoadXml(XML);
    xslt.Transform(xDoc, null, stringWriter);
    return stringWriter.ToString();
    }

    private string GetFormattedXml(string XML, string XSLFileName, System.Xml.Xsl.XsltArgumentList Arg)
    {
    System.Xml.Xsl.XslTransform xslt = new System.Xml.Xsl.XslTransform();
    xslt.Load(XSLFileName);
    System.IO.StringWriter stringWriter = new System.IO.StringWriter();
    XmlDocument xDoc = new XmlDocument();
    xDoc.LoadXml(XML);
    xslt.Transform(xDoc, Arg, StringWriter);
    return stringWriter.ToString();
    }


    See Also
    1. Sending Mail from .Net application