Monday, April 18, 2011

Adding new row to DataGridView programatically in C#

This article would be helpful if you are looking to add rows programatically to DataGridView and keeping key values invisible to user.

Heres a simple relation between ASP.Net & WinForms.

ASP.Net <--> WinForms
GridView <--> DataGridView
DataKeyNames(Considering 1 column is stored) <---> DataGridViewRow.Tag(Tag can store literally any value, but here it can solve our problem)

With the below code you have control on what you display to users while you still keep (one)important detail invisible.
Only one solution, to lengths of my knowledge, will help in this situation. Using DataGridViewRow.

List custList = GetAllCustomers();

            foreach (Customer cust in custList)
                //First add the row, cos this is how it works! Dont know why!
                DataGridViewRow R = dataGridView1.Rows[dataGridView1.Rows.Add()];
                //Then edit it
                R.Cells["Name"].Value = cust.Name;
                R.Cells["Address"].Value = cust.Address;
                R.Cells["Phone"].Value = cust.PhoneNo;
                //Customer Id is invisible but still usable, like, 
                //when double clicked to show full details
                R.Tag = cust.IntCustomerId;

Friday, April 8, 2011

Add Site-Search functionality with JRank & RESTful web service - ASP.Net

If you are looking to add Site-Search functionality to your web site, and if you dont want Google ads in your search results page, JRank comes to rescue.
Starting off with JRank is quite an easy task. Just 3 easy steps to complete.
  • Join JRank
  • Create a context. Contexts are a way to tell JRank where to search in our site, the crawl frequency and for us to know how many pages are crawled/indexed, last crawled date and other stuff.
  • Integrate search into your site. Explained below
Complete 1st and 2nd steps. The 3rd step has 3 tasks in it again.
  • Add a search box
  • Post Search Query & Get results from JRank
  • Parse & Display
Adding a search box

I suppose, search button should exist on each page that a user can access. For that purpose, I have put search box on master page. So when user searches, search data will be passed to SiteSearch.aspx.

Add SiteSearch.aspx page to your web site. This page will receive search strings from other pages in your site. Also add a Literal control to this page to display the results.
Use plain old way of passing data from one page to other.
You can also use GET or POST methods but to keep it simple, I've used post back.
In the code behind, add this code.
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        if (string.IsNullOrEmpty(sb1.Text.Trim()))
        Response.Redirect("searchresults.aspx?q=" + sb1.Text);
Post Search Query & Get results from JRank

In SiteSearch.aspx page, get the search key words from Query string and pass it to JRank to do the search.
protected void Page_Load(object sender, EventArgs e)
        if (!Page.IsPostBack)
            if (string.IsNullOrEmpty(Request.QueryString["q"].ToString().Trim()))
Parse & Display
Once JRank is called to search, it will return an XML of result that contains page details, content preview and other stuff.
I have used RESTful API as I will have more control over end result than the HTML response of JRank.
Parse it and display what you want.
private void search(string q)
        string jrankURL = string.Format("{0}&q={1}", "your-jrank-api-key", q);
        System.Net.WebClient serviceRequest = new System.Net.WebClient();
        string response = serviceRequest.DownloadString(new Uri(jrankURL));
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        XmlNode root = doc.DocumentElement;
        XmlNodeList nodes = root.SelectNodes("/serp/entries/entry");

        StringBuilder sb = new StringBuilder();
        sb.Append("Your search for ").Append(q).Append(" has ").Append(nodes.Count.ToString()).Append(" results.

    "); foreach (XmlNode node in nodes) { sb.Append("
  • ");
    string url = node["url"].InnerText;
    string title = node["title"].InnerText;
    string content = node["content"].InnerText;
  • "); } sb.Append("
"); ltSearchResults.Text = sb.ToString(); }
Try understanding the code and tweak some to get the results you need.
Happy coding!