Thursday, 20 November 2014

Add and Delete Row Manually To Gridview

No comments




.ASPX


<asp:GridView ID="GridView1" ShowFooter="True" runat="server"  AutoGenerateColumns="False" ForeColor="#333333" OnRowDataBound="GridView1_RowDataBound">                                                    
                                <Columns>
                                    <asp:TemplateField HeaderText="Sr No.">
                                        <FooterTemplate>
                                            <asp:Button ID="BtnAdd" runat="server" OnClick="Add_Click"      Text="Add Row"/>
                                        </FooterTemplate>
                                        <ItemTemplate>
                                            <%# Container.DataItemIndex+1 %>                                         
                                        </ItemTemplate>
                                        <HeaderStyle BorderColor="Black" ForeColor="White" />
                                        <ItemStyle Width="5%" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Name">
                                        <ItemTemplate>
                                            <asp:DropDownList ID="DropName" runat="server" DataTextField="InvDecs" DataValueField="InvID"
                                                TabIndex="8" Width="161px">                                               
                                            </asp:DropDownList>                                                                                   
                                        </ItemTemplate>
                                        <HeaderStyle BorderColor="Black" ForeColor="White" />
                                        <ItemStyle Width="20%" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Quantity">
                                        <ItemTemplate>
                                            <asp:TextBox ID="txtqty" runat="server"></asp:TextBox>                                                                                          
                                        </ItemTemplate>                                     
                                    </asp:TemplateField>                                                                     
                                    <asp:TemplateField>                                      
                                        <ItemTemplate>
                                            <asp:LinkButton ID="lkDelete" runat="server" onclick="Delete_Click">Delete</asp:LinkButton>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                </Columns>                             
                            </asp:GridView>



.CS


protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
             DataTable dt = (DataTable)ViewState["DT"];
            CreateDataTable();
            RowAdd();
          }
  }


public void RowAdd()
    {
        DataTable dt = new DataTable();
        dt.Rows.Add();

        GridView1.DataSource = dt;
        GridView1.DataBind();

        dt = new DataTable();     
        dt.Columns.Add("Name");
        dt.Columns.Add("Qty");

        DataRow dr = dt.NewRow();
        dr["Name"] = string.Empty;
        dr["Qty"] = string.Empty;
             
        dt.Rows.Add(dr);
        ViewState["DT"] = dt;
        GridView1.DataSource = dt;
        GridView1.DataBind();

        if (GridView1.Rows.Count == 1)
        {
            foreach (GridViewRow grow in GridView1.Rows)
            {
                GridView1.Columns[3].Visible = false;
            }
        }
        else
        {
            foreach (GridViewRow grow in GridView1.Rows)
            {
                GridView1.Columns[3].Visible = true;
            }
        }
    }

// For Message
 public void msgbox(string message)
    {
        Label lbl = new Label();
        lbl.Text = "<Script> alert (' " + message + "') </Script>";
        this.Page.Controls.Add(lbl);
    }

//Get Max Value Of Column

 public void GetMax()
    {
        SqlDataReader dr;
        SqlCommand cmd = new SqlCommand("select max(SrNo) from MyTable", con);
        con.Open();
        dr = cmd.ExecuteReader();

        if (dr.Read())
        {
            string d = dr[0].ToString();
            if (d == "")
            {
                ViewState["Max"] = "1";//set the value in viewstate which name is id
            }
            else
            {
               int r = Convert.ToInt32(dr[0].ToString());
                r = r + 1;
                ViewState["Max"] = r.ToString();
            }
        }
        dr.Close();
        cmd.Dispose();
        con.Close();
    }

//Row DataBound Event To Bind Gridview

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList dropName = (DropDownList)e.Row.FindControl("DropName");
            dropName.DataSource = dl.GridviewBind(bl);
            dropName.DataBind();
            dropName.Items.Insert(0, new ListItem("----Select----", "0"));
        }
    }


protected void CreateDataTable()
    {
        int rowIndex = 0;
        if (ViewState["DT"] != null)
        {
            dt = (DataTable)ViewState["DT"];
            DataRow dr1 = null;

            if (dt.Rows.Count > 0)
            {
                for (int i = 1; i <= dt.Rows.Count; i++)
                {             
                    DropDownList DropName= (DropDownList)GridView1.Rows[rowIndex].Cells[0].FindControl("DropName");
                    TextBox Qty = (TextBox)GridView1.Rows[rowIndex].Cells[0].FindControl("txtqty");

                    dr1 = dt.NewRow();
                    dt.Rows[i - 1]["Name"] = DropName.SelectedValue;
                    dt.Rows[i - 1]["Qty"] = Qty.Text;
                    rowIndex++;
                }
                dt.Rows.Add(dr1);
                ViewState["DT"] = dt;
                GridView1.DataSource = dt;
                GridView1.DataBind();
                if (GridView1.Rows.Count > 0)
                {
                    foreach (GridViewRow grow in GridView1.Rows)
                    {
                        GridView1.Columns[3].Visible = true;
                    }
                }
            }
        }
    }

 public void AddData()
    {
        int rowIndex = 0;
        if (ViewState["DT"] != null)
        {
            DataTable dt2 = (DataTable)ViewState["DT"];
            if (dt2.Rows.Count > 0)
            {
                for (int i = 0; i < dt2.Rows.Count; i++)
                {
                    DataRow drValues = dtValues.NewRow();

DropDownList DropName= (DropDownList)GridView1.Rows[rowIndex].Cells[0].FindControl("DropName");
               TextBox Qty = (TextBox)GridView1.Rows[rowIndex].Cells[0].FindControl("txtqty");

                    Qty.Text = dt2.Rows[i]["Qty"].ToString();                
                    DropName.SelectedValue = dt2.Rows[i]["Name"].ToString();
                    rowIndex++;
                }
            }
        }
    }
//Add Button
 protected void Add_Click(object sender, EventArgs e)
    {
        CreateDataTable();
        AddData();
    }

//Delete Row
protected void lkDelete_Click(object sender, EventArgs e)
    {
        LinkButton lk = (LinkButton)sender;
        GridViewRow gr = (GridViewRow)lk.NamingContainer;
        DataTable dt = (DataTable)ViewState["DT"];
        DataRow drow = dt.Rows[gr.RowIndex];
        drow.Delete();
        GridView1.DataSource = dt;
        GridView1.DataBind();
        if (GridView1.Rows.Count == 1)
        {
            foreach (GridViewRow grow in GridView1.Rows)
            {
                GridView1.Columns[3].Visible = false;
            }
        }
        else
        {
            foreach (GridViewRow grow in GridView1.Rows)
            {
                GridView1.Columns[3].Visible = true;
            }
        }

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            TextBox Qty = (TextBox)GridView1.Rows[i].FindControl("txtqty");
            DropDownList DropName= (DropDownList)GridView1.Rows[i].FindControl("DropName");

            Qty.Text = dt.Rows[i]["Qty"].ToString();
            if (string.IsNullOrEmpty(dt.Rows[i]["MatId"].ToString()) == false)
            {
               DropName.SelectedValue = dt.Rows[i]["Name"].ToString();
            }
         }
        ViewState["DT"] = dt;
    }

//Update Button Click To Get Record From Gridview

protected void Edit_Click(object sender, EventArgs e)
    {
        Save.Text = "Update";
        LinkButton G1 = (LinkButton)sender;
        GridViewRow gr = (GridViewRow)G1.NamingContainer;

        Label ID = (Label)gvRatio.Rows[gr.RowIndex].FindControl("lblid");
        bl.Sr = Convert.ToInt32(ID.Text);
        ViewState["Id"] = ID.Text;
        DataTable dt1 = new DataTable();
        dt1 = dl.GridviewsBind(bl);


        if (dt1.Rows.Count > 0)
        {           
            GridView1.DataSource = dt1;
            GridView1.DataBind();

            if (GridView1.Rows.Count == 1)
            {
                foreach (GridViewRow grow in GridView1.Rows)
                {
                    GridView1.Columns[3].Visible = false;
                }
            }
            else
            {
                foreach (GridViewRow grow in GridView1.Rows)
                {
                    GridView1.Columns[3].Visible = true;
                }
            }

            dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Qty");  
            DataRow dr = null;

            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                TextBox Qty = (TextBox)GridView1.Rows[i].FindControl("txtqty");             
                DropDownList DropName= (DropDownList)GridView1.Rows[i].FindControl("DropName");

                dr = dt.NewRow();
                Qty.Text = dt1.Rows[i]["Qty"].ToString();
                DropName.SelectedValue = dt1.Rows[i]["MatId"].ToString();

                dr["DropName"] = dt1.Rows[i]["DropName"].ToString();
                dr["Qty"] = dt1.Rows[i]["Qty"].ToString();             
                dt.Rows.Add(dr);
            }
        }
        ViewState["DT"] = dt;
    }
read more

Show Count Of Checkbox Checked Items Before Deleting

No comments
ASPX

<script type="text/javascript">
        function checkboxes() {
            var inputElems = document.getElementsByTagName("input"),
        count = 0;

            for (var i = 0; i < inputElems.length; i++) {
                if (inputElems[i].type == "checkbox" && inputElems[i].checked == true) {
                    count++;
                }

            }

            if (count == 0) {
                alert("No record selected");
                return false;
            }
            else {
                var agree = confirm("Are you sure ,you want to delete " + count + " Record?");
                if (agree)
                    return true;
                else
                    for (var i = 0; i < inputElems.length; i++) {
                        if (inputElems[i].checked) {
                            inputElems[i].checked = false;
                            count++;
                        }

                    }
                return false;
            }

        }
       
    </script>


<asp:Button ID="BtnDelete" OnClientClick="return checkboxes();" runat="server"  Text="Delete"/>

CS

 protected void Delete_Click(object sender, EventArgs e)
    {    
            int ans = 0;
            for (int i = 0; i < Gridview1.Rows.Count; i++)
            {            
                if ((((CheckBox)Gridview1.Rows[i].FindControl("CheckBox1")).Checked) == true)
                {
                    ans = 1;
                    bl.Sr =Convert.ToInt32((((Label)Gridview1.Rows[i].FindControl("id")).Text)); 
                    dl.Insert(bl);
                }
            }

            bindgrid();

            if (ans == 0)
            {
                msgbox("No Record Selected");
                bindgrid();
            }

            else
            {
                msgbox("Data Delete SuccessFully");
                bindgrid();
            }            
    }
read more

Wednesday, 15 October 2014

Bulk insert data into table and use cursor to insert data into another table

No comments
ASPX

 protected void Button_Click(object sender, EventArgs e)
        {
            if (fileupload.HasFile == true)
            {
                if (!Directory.Exists(Server.MapPath(@"~\ImportData\")))
                    Directory.CreateDirectory(Server.MapPath(@"~\ImportData\"));
                string path = Server.MapPath((@"~\ImportData\") + importdata.FileName);
                if (File.Exists(path))
                {
                    FileInfo f = new FileInfo(path);
                    f.Delete();
                }
                importdata.SaveAs(path);
                obj.FilePath = path;
                importData.Save(obj);
                importData.Transfer();
                lblMasage.Text = "Record Import Successfully....";
            }
        }

SP FOR   importData.Save(obj);

CREATEprocedure [dbo].[ImportData]       
@FilePath Varchar(500)     
as       
begin        
declare @sql varchar(max)            
set @sql='Truncate table temp'      
exec(@sql)      
set @sql='BULK INSERT temp FROM ''' +@FilePath+''' WITH ( DATAFILETYPE = ''char'', FIELDTERMINATOR =''                  '', ROWTERMINATOR = ''\n'' )'         
exec(@sql)      
End     


SP FOR   importData.Transfer()

CREATE procedure [dbo].[insertTemp]     
as     
begin     
declare @eid int,@dt varchar(30) 
declare chk cursor for      
select EmpId,convert(VARCHAR(30),convert(DATETIME,EmpDate,103),121) from Temp 
open chk      
fetch next from chk into @eid ,@dt      
while @@FETCH_STATUS=0      
begin   
print  @dt   
if not exists(select EmpId from temp1 where EmpId=@eid and EmpDate=@dt )      
begin      
print '1' 
INSERT INTO [temp1](EmpId,EmpDate)      
VALUES ( @eid ,@dt)      
End  
else 
begin 
print '0' 
end     
fetch next from chk into @eid ,@dt    
End      
Close chk      
DEALLOCATE chk     
end

read more

To Upload only specific extension file using javascript

No comments
JAVASCRIPT

<script type="text/javascript">
        function GetFileName(val) {
            jQuery('#<%=TextBox1.ClientID %>').val(val).trigger('change');
            return true;
        }
    </script>



    <script type="text/javascript">

        function ValidateFile(Source, args) {
            var fuData = document.getElementById('<%= importdata.ClientID %>');
            var FileUploadPath = fuData.value;
            var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
            if (Extension == "txt") {
                args.IsValid = true;
            }
            else {
                args.IsValid = false;
                document.getElementById('<%= importdata.ClientID %>').value = "";
            }
        }




ASPX


<asp:FileUpload ID="importdata" runat="server" />
 <asp:CustomValidator ID="CusFileType" runat="server" ClientValidationFunction="ValidateFile"
ControlToValidate="importdata" Display="Static" ErrorMessage="Please Select a Text File" ForeColor="Red" SetFocusOnError="True" />
read more

Get date and days based on month and year sql server

No comments
SP

CREATE   PROCEDURE [dbo].[GetDateDaily]
@Month int=null ,
@Year int=null

AS 
BEGIN 
DECLARE @DATEFROM AS DATETIME 
DECLARE @DATETO AS DATETIME 
DECLARE @FirstPart AS VARCHAR(50) 
DECLARE @HOLDER TABLE(DATE DATETIME,n varchar(50)) 
SET @DATEFROM =DATEADD(month,@Month-1,DATEADD(year,@Year-1900,0)); 
SET @DATETO = DATEADD(day,-1,DATEADD(month,@Month,DATEADD(year,@Year-1900,0)));   
 
SELECT @FirstPart = (DATENAME(WEEKDAY, (@DATEFROM))) 
INSERT INTO @HOLDER (DATE,n) 
VALUES(@DATEFROM,@FirstPart) 
WHILE @DATEFROM < @DATETO 
BEGIN 
    SELECT @DATEFROM = DATEADD(D, 1, (@DATEFROM)) 
 SELECT @FirstPart =  (DATENAME(WEEKDAY, (@DATEFROM))) 
    INSERT INTO @HOLDER(DATE,n ) 
    VALUES(@DATEFROM,@FirstPart) 
END 

select CONVERT(varchar(10),DATE,105) as DATE,n from @HOLDER


Execution

EXEC GetDateDaily 10 ,2014

output

01-10-2014    Wednesday
02-10-2014    Thursday
03-10-2014    Friday
04-10-2014    Saturday
05-10-2014    Sunday
06-10-2014    Monday
07-10-2014    Tuesday
08-10-2014    Wednesday
09-10-2014    Thursday
10-10-2014    Friday
11-10-2014    Saturday
12-10-2014    Sunday
13-10-2014    Monday
14-10-2014    Tuesday
15-10-2014    Wednesday
16-10-2014    Thursday
17-10-2014    Friday
18-10-2014    Saturday
19-10-2014    Sunday
20-10-2014    Monday
21-10-2014    Tuesday
22-10-2014    Wednesday
23-10-2014    Thursday
24-10-2014    Friday
25-10-2014    Saturday
26-10-2014    Sunday
27-10-2014    Monday
28-10-2014    Tuesday
29-10-2014    Wednesday
30-10-2014    Thursday
31-10-2014    Friday
read more

To check time entered is less than 24 hours and 60 minutes

No comments

Javascript

 function ChkTimeUp(txt) {

            var str = document.getElementById(txt).value;
            if (str.length == 2) {
                if (str > 24) {
                    alert("Hour Must be less than 24.")
                    document.getElementById(txt).value = "";
                }
                else {
                    str = str + ".";
                    document.getElementById(txt).value = str;
                }

            }
            else if (str.length == 5) {
                if (str.substring(3, 5) >= 60) {
                    alert("Minute Must be less than 60")
                    document.getElementById(txt).value = str.substring(0, 3);
                }
            }
            else if (str.length >= 5) {
                alert("Only Two Characters allowed After Decimal. ")
                document.getElementById(txt).value = str.substring(0, 3);
            }
        }


ASPX

  <asp:TextBox ID="txtInTime" Width="90%" CssClass="formTextBox" onkeyup="ChkTimeUp(this.id)"  onkeypress="return ChkPress(this.id,event)" runat="server"></asp:TextBox>
read more

Sunday, 14 September 2014

Popup Image when click on small image icon

No comments
.ASPX


 <div>
        <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Images/5.JPG" Width="90px"
            Height="90px" OnClientClick="return LoadDiv(this.src);"/>
    </div>
    <div id="divBackground">
        <div id="divImage">
            <table>
                <tr>
                    <td>
                        <img id="imgLoader" runat="server" alt="" src="" style="width: 600px; height: 600px" />
                        <img id="imgFull" runat="server" alt="" src="" style="width: 600px; height: 600px" />
                    </td>
                </tr>
                <tr>
                    <td align="center" valign="bottom">
                        <input id="btnClose" type="button" value="close" onclick="HideDiv()" />
                    </td>
                </tr>
            </table>
        </div>
    </div>


Javascript


 <script type="text/javascript">

        function LoadDiv(url) {

            var img = new Image();

            var bcgDiv = document.getElementById("divBackground");

            var imgDiv = document.getElementById("divImage");

            var imgFull = document.getElementById("imgFull");

            var imgLoader = document.getElementById("imgLoader");

            imgLoader.style.display = "block";

            img.onload = function () {

                imgFull.src = img.src;

                imgFull.style.display = "block";

                imgLoader.style.display = "none";

            };
            img.src = url;

            var width = document.body.clientWidth;

            if (document.body.clientHeight > document.body.scrollHeight) {

                bcgDiv.style.height = document.body.clientHeight + "px";

            }

            else {

                bcgDiv.style.height = document.body.scrollHeight + "px";

            }

            imgDiv.style.left = (width - 650) / 2 + "px";

            imgDiv.style.top = "20px";

            bcgDiv.style.width = "100%";



            bcgDiv.style.display = "block";

            imgDiv.style.display = "block";

            return false;

        }

        function HideDiv() {

            var bcgDiv = document.getElementById("divBackground");

            var imgDiv = document.getElementById("divImage");

            var imgFull = document.getElementById("imgFull");

            if (bcgDiv != null) {

                bcgDiv.style.display = "none";

                imgDiv.style.display = "none";

                imgFull.style.display = "none";

            }

        }
    </script>

.CSS

 #divImage
        {
            display: none;
            z-index: 1000;
            position: fixed;
            top: 0;
            left: 0;
            background-color: White;
            height: 550px;
            width: 600px;
            padding: 3px;
            border: solid 1px black;
        }
read more

Saturday, 26 July 2014

Computed column in SQL

No comments
1>Create table
2>Enter column name and datatype
3>goto column property of that column which we wants computed
4>goto Computed Column Specification
5>In formula write your computed formula

like

(case when [start_date]<=getdate() AND [end_date]>=getdate() then 'active' else 'closed' end)

or using sql query

alter table test add status as(case when [start_date]<=getdate() AND [end_date]>=getdate() then 'active' else 'closed' end)
read more

Scheduling your SP to Execute automatically every day

No comments
With help of JOB in sql we can schedule it

at first

1> Addjob name

        use msdb;
        EXEC sp_add_job @job_name = 'test',@owner_login_name ='sa'

2>which SP from Which database is to be executed

here Star is database and tst is SP

   EXEC sp_add_jobstep @job_name = 'test',
   @step_name = 'test1',
   @subsystem = 'TSQL',
   @command = 'exec tst',
   @retry_attempts = 5,
   @retry_interval = 5,
   @database_name = 'Star'

3>Assign time at which sp should be execute

   EXEC sp_add_jobschedule @job_name = 'test',
   @name = 'Scheduled Delivery',
   @freq_type = 4, -- daily
   @freq_interval = 1,   ---only once
   @active_start_time = 230000 ; ----at 11pm

here is Detail

4>Add job name to job server

EXEC sp_add_jobserver @job_name = 'test'

if showing error that sql Server Agent is not started than,

type in run Services.msc,search for sql server agent and start service

To delete Job_name

exec sp_delete_job @job_name = 'test'


More Detais from Here
read more

Monday, 21 July 2014

Crystal Report to print multiple Data

No comments
1 > create dataset and add columns
2>create new crystal report
3>add that dataset and design crystal report
4>

using Microsoft.Reporting.WebForms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

 private CrystalDecisions.CrystalReports.Engine.ReportDocument cr = new ReportDocument();
 static string Crypath = "";

protected void btnprine_Click(object sender, EventArgs e)
    {
        try
        {
            DataTable d1 = new DataTable();
            d1.TableName = "t1";
            d1.Columns.Add("Email");
            d1.Columns.Add("Address");
         
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox ck = (CheckBox)GridView1.Rows[i].FindControl("print");
                if (ck.Checked == true)
                {
                    Label id = (Label)GridView1.Rows[i].FindControl("Label5");
                    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Example"].ToString());
                    SqlCommand cmd = new SqlCommand("SP", con);
                    cmd.Parameters.AddWithValue("@id", id.Text);
                    cmd.CommandType = CommandType.StoredProcedure;
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    DataRow drow = ds.Tables[0].Rows[0];
                    DataRow dr1 = d1.NewRow();                 
                    dr1["Email"] = drow["Email"];
                    dr1["Address"] = drow["Address"];                  
                    d1.Rows.Add(dr1);
                    Crypath = Server.MapPath("~/CrystalReport.rpt").ToString();
                    cr.Load(Crypath);
                    cr.Database.Tables[0].SetDataSource(d1);
                    cr.Refresh();
                }
            }
            Cry("_Report");
        }
        catch(Exception)
        {
           
        }
    }
    public void Cry(string titlename)
    {
        cr.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, titlename);
    }


Another Way

In Report Page

         {


        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable ds = new DataTable();
        da.Fill(ds);

        DataView dv = new DataView(ds);

        if (Txt_Search_name.Text != "")
        {
            dv.RowFilter = "name LIKE '" + Txt_Search_name.Text.TrimEnd() + "%'";
            dv.RowStateFilter = DataViewRowState.CurrentRows;
            HttpContext.Current.Session["Para1"] = Txt_Search_name.Text.TrimEnd() + "%'";
        }
        else
        {
            HttpContext.Current.Session["Para1"] = "All";
        }

        if (Txt_Search_Mobile.Text == "")
        {
            HttpContext.Current.Session["Para2"] = "All";
        }
        else
        {
            HttpContext.Current.Session["Para2"] = Txt_Search_Mobile.Text;
        }

        if (DD_KYC.SelectedIndex == 0)
        {
            HttpContext.Current.Session["Para3"] = "All";
        }       
        else
        {
            HttpContext.Current.Session["Para4"] = DD_Type.SelectedValue;
        }
        DataTable dt = new DataTable();
        dt = dv.ToTable();
        HttpContext.Current.Session["DatatableReport"] = dt;
        GridView_data.DataSource = dt;
        GridView_data.DataBind();
    }
    protected void imgpdf_Click(object sender, ImageClickEventArgs e)
    {
        Btn_Search_Click(sender, e);
        string url = "Default_report.aspx?Name=List";
        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "NewWindow", "window.open('" + url + "','_blank');", true);
    }
 

Create New Default_report.aspx




if (Request.QueryString["Name"] != null)
            {
                if (Request.QueryString["Name"] == "List")
                {
                    DataTable dt1 = new DataTable();
                    dt1 = (DataTable)HttpContext.Current.Session["DatatableReport"];          
                    ReportDocument crystalReport = new ReportDocument();
                    crystalReport.Load(Server.MapPath("../Reports/xyz.rpt"));
                    crystalReport.SetDataSource(dt1);
                    crystalReport.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "_Report");
                    //CrystalReportViewer1.ReportSource = crystalReport;
                    //CrystalReportViewer1.DataBind();
                }
}



For Loading PDF In Browser

 protected void Download_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Conection"].ToString());
        SqlCommand cmd = new SqlCommand("reg", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@RegNo", No.Text);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable ds = new DataTable();
        da.Fill(ds);

        ReportDocument crystalReport = new ReportDocument();

        if (lblChlnNo.Text.Contains("T"))
        {
            crystalReport.Load(Server.MapPath("../Reports/Report.rpt"));
        }
     
        crystalReport.SetDataSource(ds);
      
        try
        {
            ExportOptions CrExportOptions;
            DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
            PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
            CrDiskFileDestinationOptions.DiskFileName = Server.MapPath(@"../Reports/AllReport" + No.Text + ".pdf");
            CrExportOptions = crystalReport.ExportOptions;
            {
                CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
                CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
                CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
                CrExportOptions.FormatOptions = CrFormatTypeOptions;
            }
            crystalReport.Export();
        }
        catch (Exception ex)
        {

        }

        string url = "../Stores/Default_report.aspx?Name=Rpt_No";
        HttpContext.Current.Session["url"] = "../Reports/AllReport" + No.Text + ".pdf");

        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "NewWindow", "window.open('" + url + "','_blank');", true);
        clear();

    }

 

in Default.aspx

 

 if (Request.QueryString["Name"] == "Rpt_No")
                {                 
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "NewWindow", "window.open('" + HttpContext.Current.Session["url"] + "','_self');", true);
                }


 








read more