Pages

Tuesday, 27 March 2012

Export data to Word from the grid view


 protected void word_Click(object sender, ImageClickEventArgs e)
    {
        grdCategory.AllowPaging = false;
        grdCategory.DataBind();
        Response.ClearContent();
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "SetaDirectory.doc"));
        Response.Charset = "";
        Response.ContentType = "application/ms-word";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        grdCategory.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }

Export data to Excel from the Grid View



--> take one button in click event write this code
protected void Excel_Click(object sender, ImageClickEventArgs e)
    {
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "SetaDirectory.xls"));
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        grdCategory.AllowPaging = false;
        grdCategory.DataBind();
        //Change the Header Row back to white color
        grdCategory.HeaderRow.Style.Add("background-color", "#FFFFFF");
        //Applying stlye to gridview header cells
        for (int i = 0; i < grdCategory.HeaderRow.Cells.Count; i++)
        {
            grdCategory.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
        }
        int j = 1;
        //This loop is used to apply stlye to cells based on particular row
        foreach (GridViewRow gvrow in grdCategory.Rows)
        {
            gvrow.BackColor = System.Drawing.Color.White;
            if (j <= grdCategory.Rows.Count)
            {
                if (j % 2 != 0)
                {
                    for (int k = 0; k < gvrow.Cells.Count; k++)
                    {
                        gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
                    }
                }
            }
            j++;
        }
        grdCategory.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();

    }

public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }


--------------------------------------sriraj--------------------------------------------

Monday, 26 March 2012

How to Use Pager Template in Grid View


Design code: First Take grid view in page

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging"
        OnDataBound="GridView1_DataBound" AutoGenerateColumns="False" DataKeyNames="CustomerID"
        DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />
            <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
            <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
           <asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle" SortExpression="ContactTitle" />
            <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
            <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
        </Columns>
        <PagerTemplate>
            <table width="100%">
                <tr>
                    <td style="text-align: right">
                        <asp:PlaceHolder ID="PlaceHolder1" runat="server" />
                    </td>
                </tr>
            </table>
        </PagerTemplate>
    </asp:GridView>

After taking the grid view goto Code Follow this code.
C#

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{          
      GridView1.PageIndex = e.NewPageIndex;                    
}

protected void GridView1_DataBound(object sender, EventArgs e)
{
      SetPaging();
}

private void SetPaging()
{
      GridViewRow row = GridView1.BottomPagerRow;
      int alphaStart = 65;
         
      for (int i = 1; i < GridView1.PageCount; i++)
      {              
            LinkButton btn = new LinkButton();
            btn.CommandName = "Page";
            btn.CommandArgument = i.ToString();

            if (i == GridView1.PageIndex + 1)
            {
                  btn.BackColor = Color.BlanchedAlmond;
            }

            btn.Text = Convert.ToChar(alphaStart).ToString();
            btn.ToolTip = "Page " + i.ToString();
            alphaStart++;
PlaceHolder place = row.FindControl("PlaceHolder1") as PlaceHolder;
            place.Controls.Add(btn);

            Label lbl = new Label();
            lbl.Text = " ";
            place.Controls.Add(lbl);
      }
}
-----------------------------sriraj----------------------

Sunday, 25 March 2012

How to display records if its not exist in another table


SELECT Cid,Cname
FROM   Directory
WHERE  NOT EXISTS
  (SELECT *
   FROM   CompanyLoginDetails
   WHERE  CompanyLoginDetails.CompanyName = Directory.Cname)
end

SELECT  *
FROM    Directory
WHERE   Cname IN (SELECT CompanyName FROM CompanyLoginDetails)

Thursday, 22 March 2012

How to Download a file from the Data Base


//First find the File name from the data base then only it will work

protected void imgbtnDwnld_Click(object sender, ImageClickEventArgs e)
    {
        string strSId = ((ImageButton)sender).Attributes["Filename"].ToString().Trim();
     
        string filename = Server.MapPath(strSId.ToString());
        FileInfo fileInf = new FileInfo(filename);
        if (fileInf.Exists)
        {
            Response.Clear();
            Response.AddHeader("Content-Disposition", "inline;attachment; filename=" + fileInf.Name);
            Response.AddHeader("Content-Length", fileInf.Length.ToString());
            Response.ContentType = "application/octet-stream";
            Response.Flush();
            Response.TransmitFile(fileInf.FullName);
            Response.End();
        }
        else
        {
            ShowActionMessage("Sorry unable to display the price list right now.");
        }

    }


 private void ShowActionMessage(string Message)
    {
        string message = Message;

        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        sb.Append("<script type = 'text/javascript'>");

        sb.Append("window.onload=function(){");

        sb.Append("alert('");

        sb.Append(message);

        sb.Append("')};");

        sb.Append("</script>");

        ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
    }

How to Find Grid View in Inner Grid View



 protected void grdCategory_RowDataBound(object sender, GridViewRowEventArgs e)
    {

 if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView row = (DataRowView)e.Row.DataItem;
            Label lblTitleId = (Label)e.Row.FindControl("lblId");
            //LinkButton lnkbtnCategory = (LinkButton)e.Row.FindControl("lbtnCategory");
            GridView grdSubCategory = (GridView)e.Row.FindControl("grdsubcat");
}
}
//Binding data to Inner Grid View Based On Main Grid View Id

protected void grdSubCategory_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView row = (DataRowView)e.Row.DataItem;
            LinkButton lnkbtnSubCategory = (LinkButton)e.Row.FindControl("lblproduct");
            lnkbtnSubCategory.Text = row["ProductName"].ToString();
            lnkbtnSubCategory.Attributes["SubCategoryId"] = row["ProductId"].ToString();
            lnkbtnSubCategory.Attributes["SubCategoryName"] = row["ProductName"].ToString();
        }
    }

How to Add Videos to Datalist control


<table width="100%" border="0" cellspacing="0" cellpadding="2">
                                    <tr>
                                      <td>
                                          <asp:Literal ID="Literal1" runat="server"></asp:Literal>
                                        </td>
                                    </tr>
                                    <tr>
                                      <td>
                                          <asp:DataList ID="galleryDataList" runat="server"
                                              onitemdatabound="galleryDataList_ItemDataBound" RepeatColumns="2" Width="100%">
                                              <ItemTemplate>
                                                  <table width="100%">
                                                      <tr>
                                                          <td>
                                                              <input id="hdnVideoPath" runat="server" type="hidden"
                                                                  value='<%#DataBinder.Eval(Container.DataItem,"VideoPath") %>' />
                                                              <input id="hdnId" runat="server" type="hidden"
                                                                  value='<%#DataBinder.Eval(Container.DataItem,"VideoPathId") %>' />
                                                              <asp:Literal ID="Literalvideo" runat="server"></asp:Literal>
                                                          </td>
                                                      </tr>
                                                  </table>
                                              </ItemTemplate>
                                          </asp:DataList>
                                        </td>
                                    </tr>
                                  </table>

protected void galleryDataList_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            try
            {

                HtmlInputHidden hdnpath1 = (HtmlInputHidden)e.Item.FindControl("hdnVideoPath");
                Literal literalvalue = (Literal)e.Item.FindControl("Literalvideo");
                if (!string.IsNullOrEmpty(hdnpath1.Value))
                {
                    literalvalue.Text = "<iframe title='YouTube video player' width='300' height='200' src='" + hdnpath1.Value + "' frameborder='0' allowfullscreen></iframe>";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

Friday, 2 March 2012

How to Bind The Data to Data List Control In Side The Grid View


protected void grvExpendabael_RowDataBound(object sender, GridViewRowEventArgs e)
    {
     

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            GridView grdFamilymember = (GridView)e.Row.FindControl("grdFamilyMember");
         
           
            SqlCommand cmd = new SqlCommand("GetProductById1", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter p1 = new SqlParameter("@CiD", SqlDbType.Int);
            p1.Value = 1;
            cmd.Parameters.Add(p1);
            con.Open();
            cmd.ExecuteNonQuery();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            da.Fill(ds, "GetProductById1");
            // galleryDataList.
            DataList dss = (DataList)e.Row.FindControl("galleryDataList");
            dss.DataSource = ds;
            dss.DataBind();
            con.Close();

        }
    }

How to Put Data List Control In Data Grid View


<asp:GridView ID="grvExpendabael" runat="server" Width="660px" AutoGenerateColumns="false"
                            GridLines="None" OnRowDataBound="grvExpendabael_RowDataBound"
                            onrowcommand="grvExpendabael_RowCommand">
                            <Columns>
                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <table width="660px">
                                            <tr>
                                                <td>
                                                    <h3 class="menuheader expandable" style="margin-bottom: 5px;">
                                                        <asp:LinkButton  ID="lblTitle" runat="server" Text='<%#Bind("CName") %>' Font-Underline="false" ForeColor="#706e6e" CommandArgument='<%#Bind("Cid") %>' CommandName="Select"></asp:LinkButton></h3>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>
                                                    <ul class="categoryitems">
                                                        <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                                            <tr>
                                                                <td>
                                                                    <div class="model_img">
                                                                        <asp:DataList ID="galleryDataList" RepeatColumns="4" runat="server" OnItemCommand="galleryDataList_ItemCommand">
                                                                            <ItemTemplate>
                                                                                <div class="image_1">
                                                                                    <asp:Image ID="imgGallery" runat="server" ImageUrl='<%#Bind("PimagePath")%>' Width="50px"
                                                                                        Height="50px" />
                                                                                </div>
                                                                                <div class="text">
                                                                                    <h3>
                                                                                        <asp:Label ID="lblModel" runat="server" Text='<%#Bind("ModelName")%>'></asp:Label>
                                                                                    </h3>
                                                                                    <p>
                                                                                        <asp:Label ID="Label1" runat="server" Text='<%#Bind("Price")%>'></asp:Label></p>
                                                                                </div>
                                                                            </ItemTemplate>
                                                                        </asp:DataList>
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                        </table>
                                        </table>
                                        </ul> </td> </tr> </table>
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                        </asp:GridView>