Tuesday, July 12, 2011

GridView control provides very flexible way to display, select, sort or edit data on ASP.NET page with ease but it does not provide an easy way to create nested grid to display master details views of your database tables. By nesting I mean you are trying to put one GridView inside another GridView to display better details view for the users. In this tutorial I will show you how easy it is to implement nested GridView scenario with minimum code.


In this tutorial I am showing Categories and Products tables from Northwind database. I hope you also have Northwind sample database available to you otherwise download it from the Microsoft website.

Following code shows the HTML markup of GridView control on the page. Notice how I am using TemplateField column to add a Label and a nested GridView view control inside the MainGridView control. TemplateField column provides you option to add any number of ASP.NET controls inside GridView in one of its Template. For this tutorial I am using ItemTemplate as I want to show InnerGridView for all the items in the MainGridView.
<asp:GridView ID="MainGridView" runat="server" AutoGenerateColumns="False"
   CellPadding="6" Width="50%" Font-Names="Arial" GridLines="None" BorderColor="#000000"
   BorderStyle="Solid" BorderWidth="1px">

   <Columns>
      <asp:TemplateField HeaderText="Categories and Products">
         <ItemTemplate>
          
            <asp:Label runat="server" ID="lblCategoryName" Text='<%# Eval("CategoryName") %>'
               Font-Bold="True" Font-Size="12pt" />

            <asp:GridView ID="InnerGridView" runat="server" CellPadding="4" Width="100%"
               DataSource='<%# GetProductsByCategory(Eval("CategoryID").ToString()) %>'
               BorderStyle="Solid" BorderWidth="1px" Font-Size="8pt"
               BorderColor="#336699" GridLines="Horizontal">
          
               <HeaderStyle BackColor="#336699" Font-Bold="True" ForeColor="White" />
            </asp:GridView>

         </ItemTemplate>
      </asp:TemplateField>
   </Columns>

   <HeaderStyle BackColor="#000000" Font-Bold="True" ForeColor="White" Font-Size="10pt" />
</asp:GridView>
The most important line in the above code is where I am setting the DataSource property of the nested GridView control using ASP.NET binding expression. In the expression I am calling a custom method GetProductsByCategory which takes category id as its only parameter from the main GridView control and return the products DataTable to inner GridView control. In some online articles you will also see people using RowDataBound event of the MainGridView control to achieve the similar functionality but I have found this technique easier to implement.

Following is the C# code of the page. In the Page_Load event I am simply loading and binding categories with the MainGridView control. You will find code in GetProductsByCategory very similar to LoadCategories with only one difference that it fetches Products from Northwind database which are only available in a particular category.
protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack)
  {
      LoadCategories();
  }
}

private void LoadCategories()
{
   string constr = @"Server=TestServer;Database=NORTHWND;uid=test; pwd=test;";
   string query = "SELECT TOP 3 CategoryID, CategoryName FROM Categories";

   SqlDataAdapter da = new SqlDataAdapter(query, constr);
   DataTable table = new DataTable();

   da.Fill(table);

   MainGridView.DataSource = table;
   MainGridView.DataBind();
}

public DataTable GetProductsByCategory(string categoryId)
{
   string constr = @"Server=TestServer;Database=NORTHWND;uid=test; pwd=test;";
   string query = "SELECT Top 3 ProductID, ProductName, UnitPrice FROM Products WHERE CategoryID = " + categoryId;

  SqlDataAdapter da = new SqlDataAdapter(query, constr);
  DataTable table = new DataTable();

  da.Fill(table);
  return table;
}

Monday, July 4, 2011

Monday, May 23, 2011

How to add the dynamic controls [ java script ]


<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT language="javascript">
function add(type) {

    //Create an input type dynamically.
    var element = document.createElement("input");

    //Assign different attributes to the element.
    element.setAttribute("type", type);
    element.setAttribute("value", type);
    element.setAttribute("name", type);

    var foo = document.getElementById("fooBar");

    //Append the element in page (in span).
    foo.appendChild(element);

}
</SCRIPT>
</HEAD>
<BODY>
<FORM>

Select the element and click Add to add it in form.
<BR/>
<SELECT name="element">
    <OPTION value="button">Button</OPTION>
    <OPTION value="text">Textbox</OPTION>
    <OPTION value="radio">Radio</OPTION>
</SELECT>

<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value)"/>

<span id="fooBar">&nbsp;</span>

</FORM>
</BODY>
</HTML>


Sunday, May 22, 2011

simple File Upload

string filename = FileUpload1.FileName;
        FileUpload1.SaveAs(Server.MapPath("~/css/") + filename);


FileUpload1 is the  ID of file upload control.

~/css   is the folder to which we are up

Monday, March 21, 2011

  if (ds.Tables[0].Rows.Count > 0)
                    {
                        Session["Uid"] = ds.Tables[0].Rows[0]["User_Id"].ToString();
                

Wednesday, March 2, 2011

One click DOWN LOAD DOCUMENT

  string textFile = string.Format("{0}.txt", DateTime.Now.ToString("MM-dd-yyyy_HH-mm-ss"));
 System.IO.StreamWriter streamWriter = File.CreateText(string.Format(@"{0}{1}", "D:\\", textFile));
  streamWriter.WriteLine(Textbox.Text); //( pass the string from which you want get input to write in the doc.)
            streamWriter.Close();
above  works for local


For server :

           textFile = string.Format("{0}.txt", DateTime.Now.ToString("MM-dd-yyyy_HH-mm-ss"));
           // string textFile = string.Format("{0}.txt", DateTime.Now.ToString("MM-dd-yyyy"));
             string kk = string.Format(@"{0}{1}", Server.MapPath("Download/"), textFile).ToString();
            System.IO.StreamWriter streamWriter = File.CreateText(string.Format(@"{0}{1}", Server.MapPath("Download/"), textFile));
            streamWriter.WriteLine(download_htmlcode.ToString());
            streamWriter.Close();

            HttpContext.Current.Response.ContentType = "application/octet-stream";
            //HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(kk));
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename="+"Yourdesign");
        
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.WriteFile(kk);
            HttpContext.Current.Response.End();

Thursday, February 24, 2011

how to include multiple double coats[ " "] in the string

string s="select * from emp where emp(\"temp1\")";

o/p  :            select * from emp where emp("temp1")

string k= "<input name=\"item_name_" + k.ToString() + "\" type=\"hidden\" value=\"" +k.ToString() + "\"> ";        
                 <input name="item_name_anil" type="hidden" value="anil">