Monday 21 October 2013

Export gridview to excel in asp.net

protected void btnExport_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
        dt.Columns.Add("Sr No");
        dt.Columns.Add("Qty");
        dt.Columns.Add("Rate");

        foreach (gridviewrow item in gridview.Rows)
        {
           
                DataRow dr = dt.NewRow();
                dr["Sr No"] = item["colOrderSrNo"].Text;
                dr["Qty"] = item["colOrderQty"].Text;
                dr["Rate"] = item["colUnitRate"].Text;
;
                dt.Rows.Add(dr);
        }
        if (dt == null)
        {
            throw new Exception("No record found for export");
        }
        string Path = "D:\\FileName" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + ".xls";
        FileInfo FI = new FileInfo(Path);
        if (!FI.Exists)
        {
           
        }
        else
        {
            FI.Delete();
        }
        StringWriter stringWriter = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
        DataGrid DataGrd = new DataGrid();
        DataGrd.DataSource = dt;
        DataGrd.DataBind();

        DataGrd.RenderControl(htmlWrite);
        string directory = Path.Substring(0, Path.LastIndexOf("\\"));
        if (!Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }
        System.IO.StreamWriter vw = new System.IO.StreamWriter(Path, true);
        stringWriter.ToString().Normalize();
        vw.Write(stringWriter.ToString());
        vw.Flush();
        vw.Close();
        WriteAttachment(FI.Name, "application/vnd.ms-excel", stringWriter.ToString());


}




 public static void WriteAttachment(string FileName, string FileType, string content)
    {
        try
        {
            HttpResponse Response = System.Web.HttpContext.Current.Response;
            Response.ClearHeaders();
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
            Response.ContentType = FileType;
            Response.Write(content);
            Response.End();
        }
        catch (Exception ex)
        {

        }
    }

Saturday 19 October 2013

get row index and data column associated with row index

GridDataItem rows = (GridDataItem)(((ImageButton)e.CommandSource).NamingContainer);
                int varName1 = Convert.ToInt32(((Label)rows.FindControl("lblSRNO")).Text.ToString());

Monday 14 October 2013

query string example

"../Radiology/EMR.aspx?&dReqId=" + Session[SessionVariable.ot_Req_no].ToString() + "&dVmId=" + Session[HMISWEB.SessionVariable.vmid].ToString() + "&strVisitType=" + Session[SessionVariable.OT_Visit_Type].ToString() + "&strModify_YN=N" + "&strDeptTemplateType=S" + "&dDocId=0" + "&strAccessString=Y";

Serial Number For grid view

<telerik:GridTemplateColumn UniqueName="SRNO" AllowFiltering="false" HeaderText="Sr No">
                                                            <ItemTemplate>
                                                               <asp:Label ID="lblSRNO" runat="server" ></asp:Label>
                                                            </ItemTemplate>
                                                            <HeaderStyle Width="5%" />
                                                            <ItemStyle Width="5%" />
                                                        </telerik:GridTemplateColumn>




protected void rdgAddedItems_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            Label lbl = e.Item.FindControl("lblSRNO") as Label;
            lbl.Text = (e.Item.ItemIndex + 1).ToString();
        }
    }

Wednesday 19 June 2013

display image in image control from file upload control

string path = Server.MapPath("Images/") + FileUpload1.PostedFile.FileName;
            FileUpload1.SaveAs(path);
            Image3.ImageUrl = "Images/" + FileUpload1.PostedFile.FileName;

Tuesday 12 March 2013

how to access controls on another form c#

Form1 with 1 textbox and button
this button is for opening new form (form2)

Form2 with datagridview and button is for sending datagraidview value to textbox on Form1


On Form1
 private void button_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2(this);
            f2.Show();
        }

On Form2

 public Form2()
        {
            InitializeComponent();
        }

        private Form1 f1 = null;


        public Form2(Form callingForm)
        {
            f1 = callingForm as Form1;
            InitializeComponent();
        }

private void button_Click(object sender, EventArgs e)
        {
            this.f1.TextBox = dataGridView1.SelectedRows[0].Cells["columnname"].Value.ToString();
            this.Close();         
        }

Wednesday 27 February 2013

how to clear all textbox in asp.net

protected void Button1_Click(object sender, EventArgs e)
        {
            ClearInputs(Page.Controls);
        }
        void ClearInputs(ControlCollection ctrls)
        {
            foreach (Control ctrl in ctrls)
            {
                if (ctrl is TextBox)
                    ((TextBox)ctrl).Text = string.Empty;
                ClearInputs(ctrl.Controls);
            }
        }

Monday 18 February 2013

check if record already exists access



SqlConnection con = new SqlConnection(strConnString);
            SqlCommand cmdCount = new SqlCommand("select count(*) from customers where name='" + txtCustomername.Text + "'", con);
            con.Open();
            int count = (int)cmdCount.ExecuteScalar();
            if (count > 0)
            {
                lblMessage.Text = "Customer already exists";
                lblMessage.Visible = true;
            }
            else
            {
                Insert query
            }
            con.Close();

Saturday 16 February 2013

bind dropdownlist in asp.net using dataset

 protected void BindCustomerNameddl()
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("Select cid,name FROM memberLogin", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            ddlCustomername.DataSource = ds;
            ddlCustomername.DataTextField = "name";
            ddlCustomername.DataValueField = "cid";
            ddlCustomername.DataBind();
            ddlCustomername.Items.Insert(0, new ListItem("--Select--", "0"));
            con.Close();
        }

Thursday 31 January 2013

concatenate two strings in crystal report


Field exporer---- Formula field------create new


{Employee.employeeFirstName}+" "+{Employee.employeeMiddleName}+" "+{Employee.employeeLastName}

Tuesday 29 January 2013

move listbox items to another listbox in c#

// all items moves from left listbox to right


int count = listBox1.Items.Count;//assigning items in listbox it into count variable
            if (count != 0)//checking the conditions
            {
                for (int i = 0; i < count; i++)
                {
                    listBox2.Items.Add(listBox1.Items[i]);
                }
            }

            listBox1.Items.Clear();//clear the listbox after transfering records.


//only selected item move to right listbox


if (listBox1.SelectedIndex > -1)
            {
                listBox2.Items.Add(listBox1.SelectedItem);//transfer records from listbox1 to Listbox2 on select records..
                listBox1.Items.Remove(listBox1.SelectedItem);

            }

//only selected item move to left listbox


if (listBox2.SelectedIndex > -1)
            {
                listBox1.Items.Add(listBox2.SelectedItem);
                listBox2.Items.Remove(listBox2.SelectedItem);
            }

// all items moves from right listbox to left


int count = listBox2.Items.Count;
            if (count != 0)
            {
                for (int i = 0; i < count; i++)
                {
                    listBox1.Items.Add(listBox2.Items[i]);
                }
            }
            listBox2.Items.Clear();


display data in listview c#


string SQL = "SELECT departmentName FROM Department";
            source.View = View.Details;

            OleDbConnection con = new OleDbConnection(connectionString);
            OleDbCommand cmd = new OleDbCommand(SQL, con);
            OleDbDataReader r = null;

            con.Open();
            r = cmd.ExecuteReader();
            for (int i = 0; i <= r.FieldCount - 1; i++)
            {
                source.Columns.Add("Column " + (i + 1).ToString(), 200, HorizontalAlignment.Left);
            }
            while (r.Read())
            {
                ListViewItem lvItem = new ListViewItem(r[0].ToString());
                for (int i = 1; i <= r.FieldCount - 1; i++)
                {
                    lvItem.SubItems.Add(r[i].ToString());
                }
                source.Items.Add(lvItem);
            }
            con.Close();

display data in listbox c#


private void displayDataInListBox()
        {
            try
            {
                OleDbConnection connection = new OleDbConnection(connectionString);
                OleDbDataAdapter da = new OleDbDataAdapter();
                connection.Open();
                OleDbDataReader Dr;
                OleDbCommand command1 = new OleDbCommand("SELECT departmentName FROM Department", connection);
                command1.ExecuteNonQuery();
                Dr = command1.ExecuteReader();
                listBox1.Items.Clear();
                while (Dr.Read())
                {

                    listBox1.Items.Add(Dr.GetString(0).ToString());

                }
                Dr.Close();
            }
            catch (OleDbException ex)
            {
                MessageBox.Show(ex.Message);
            }
          
        }

how to create multiple textbox at runtime in c#.net


public void createTextBox()
        {
            TextBox[] txtTextBox = new TextBox[10];

            for (int u = 0; u < txtTextBox.Count(); u++)
            {
                txtTextBox[u] = new TextBox();
            }
            int i = 0;
            foreach (TextBox txt in txtTextBox)
            {
                string name = "TextBoxName" + i.ToString();

                txt.Name = name;
                txt.Text = name;
                txt.Location = new Point(0, 32 + (i * 28));
                txt.Visible = true;
                this.Controls.Add(txt);
                i++;
            }
        }