Monday, 20 May 2013

How to make the Date Time format in C#.net using DateTime Format


//=================Tochange the Date Format from MM/dd/yyyy to dd/MM/yyyy================//

       //First Assign the Date Value to a String Variable
         string urDate_Of_Appointment = TxtDateOfApp.Text; 

//Then declare a object of the method of System Define for DateTime Format  
    System.Globalization.DateTimeFormatInfo dateDate_Of_AppointmentInfo = new System.Globalization.DateTimeFormatInfo();

//Then Assign the format of the Date(dd/MM/yyy) to DateTimeFormatInfo
            dateDate_Of_AppointmentInfo.ShortDatePattern = "dd/MM/yyyy";

//Then assign the value to variable as per your DateTime Format
            DateTime validDate_Of_Appointment = Convert.ToDateTime(urDate_Of_Appointment, dateDate_Of_AppointmentInfo);

 // Assign the  value to the class object which we declare Here(Date_Of_Appointment  is variable of a object class)    
 obj.Date_Of_Appointment = validDate_Of_Appointment.ToString();

                                   OR




       string RetDateTime(string srcdate)
        {
            string resdate = "";
            try
            {
                string[] arr = srcdate.Split('/');
                if (arr.Length > 0)
                {
                    resdate = arr[2] + "/" + arr[1] + "/" + arr[0];
                }
            }
            catch (Exception)
            {
            }
            return resdate;
        }

//Apply in Control

                  generatex.FrmDate = RetDateTime(FromDate.Text); ;
                  generatex.ToDate = RetDateTime(ToDate.Text); 



Thanks
Satyabrata Behera
            

Save/Import/Export the Excel/Word File in the local Drive In window Application


Save the Excel File in the local Drive
try
{
string path = "";
string[] Pathlist = Application.StartupPath.Split('\\');
foreach (var item in Pathlist)
{
if (item.ToString() == "bin")
{
break;
}
else
{ path += item + "\\";
}
}
path += @"FileUploads\Template\DJIL.xlsx";
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel Files (*.xlsx)|*.xlsx|All Files (*.*)|*.*";
saveFileDialog1.FileName = "DJIL.xlsx";
saveFileDialog1.FilterIndex = 1;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string StaticPath = Application.StartupPath + "DJIL.xlsx";
FileInfo p = new FileInfo(saveFileDialog1.FileName.ToString());
if (p.Name == "DJIL.xlsx")
{
if (File.Exists(saveFileDialog1.FileName))
{
System.IO.File.Delete(saveFileDialog1.FileName);
}
System.IO.File.Copy(path, saveFileDialog1.FileName);
File.SetAttributes(saveFileDialog1.FileName, FileAttributes.Normal);
System.Diagnostics.Process.Start(saveFileDialog1.FileName);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Import Excel Data To a GridView
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = ("Excel Files (*.xlsx)|*.xlsx");
DialogResult dlgResult = dlg.ShowDialog();
if (dlgResult == DialogResult.OK)
{
Path = dlg.FileName;
LoadExcelData();
}

private void LoadExcelData()
{
if (System.IO.File.Exists(Path))
{
string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", Path);
string query = String.Format("select * from [{0}$]", "Sheet1");
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
DataGridView1.DataSource = dataSet.Tables[0];
}
else
{
MessageBox.Show("No File is Selected");
}
}



After Import Excel Data To a GridView Save it to DataBase
try
{
POS_StoreRoom objImportItems = new POS_StoreRoom(); ;
DataTable dt = new DataTable();
dt.Columns.Add("Item_Name", typeof(string));
dt.Columns.Add("Variation_Name", typeof(string));
dt.Columns.Add("Barcode", typeof(string));
dt.Columns.Add("Quantity", typeof(int));
dt.Columns.Add("Cost", typeof(decimal));
dt.Columns.Add("Price", typeof(decimal));

for (int i = 0; i < dgvExcelData.RowCount - 1; i++)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < dgvExcelData.ColumnCount; j++)
{
if (dgvExcelData[j, i].Value != null)
{
dr[j] = dgvExcelData[j, i].Value.ToString();
//dt.Rows.Add(dgvExcelData[0, i].Value.ToString(), dgvExcelData[1, i].Value.ToString(), dgvExcelData[2, i].Value.ToString(), dgvExcelData[3, i].Value.ToString(), dgvExcelData[4, i].Value.ToString(), dgvExcelData[5, i].Value.ToString());
}
}
dt.Rows.Add(dr);
}
//dgvExcelData.DataSource = dt;
if (dt.Rows.Count > 0)
{
objImportItems.ImportItems = dt;
ERPManagement.GetInstance.InsertImportItems(objImportItems);
}
}
catch (Exception Ex1)
{
MessageBox.Show(Ex1.ToString(), "Error", MessageBoxButtons.OK);
}

A Page Has Multiple Check Box How to Unchek all CheckBox At a time


 void Uncheck()
        {
            foreach (Control Chk in this.Controls)
            {
                if (Chk.GetType() == typeof(Panel))
                {
                    foreach (Control ct in ((Panel)Chk).Controls)
                    {
                        if (ct.GetType() == typeof(CheckBox))
                        {
                            ((CheckBox)ct).Checked = false;
                        }
                    }
                }
            }
        }

Thursday, 25 April 2013

Calculator In Window Application



 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        double firstno = 0; // First number will initially zero
        string sign = "+";  // Initial sign is "+" it may be "-","*","/"
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void BtnOne_Click(object sender, EventArgs e)
        {
            TxtCalc.Text += BtnOne.Text;   // button 1 Text is "1"
        }

        private void BtnTwo_Click(object sender, EventArgs e)
        {
            TxtCalc.Text += BtnTwo.Text;
        }

        private void BtnThree_Click(object sender, EventArgs e)
        {
            TxtCalc.Text += BtnThree.Text;
        }

        private void BtnFour_Click(object sender, EventArgs e)
        {
            TxtCalc.Text += BtnFour.Text;
        }

        private void BtnFive_Click(object sender, EventArgs e)
        {
            TxtCalc.Text += BtnFive.Text;
        }

        private void BtnSix_Click(object sender, EventArgs e)
        {
            TxtCalc.Text += BtnSix.Text;
        }

        private void BtnSeven_Click(object sender, EventArgs e)
        {
            TxtCalc.Text += BtnSeven.Text;
        }

        private void BtnEight_Click(object sender, EventArgs e)
        {
            TxtCalc.Text += BtnEight.Text;
        }

        private void BtnNine_Click(object sender, EventArgs e)
        {
            TxtCalc.Text += BtnNine.Text;
        }

        private void BtnZero_Click(object sender, EventArgs e)
        {
            TxtCalc.Text += BtnZero.Text;
        }

        private void BtnDot_Click(object sender, EventArgs e)
        {
            TxtCalc.Text += BtnDot.Text;
        }

        private void BtnPlus_Click(object sender, EventArgs e)  // Button Add Click Event
        {
            sign = "+";                              // sign will be "+" for identification
            firstno = Convert.ToDouble(TxtCalc.Text);       //convert value in textbox to double and put it in firstno
           TxtCalc.Text = "";
        }

        private void BtnSubstraction_Click(object sender, EventArgs e)// Button SUBTRACT Click Event
        {
            sign = "-";
            firstno = Convert.ToDouble(TxtCalc.Text);
            TxtCalc.Text = "";
        }

        private void BtnMultiplication_Click(object sender, EventArgs e)
        {
            sign = "*";
            firstno = Convert.ToDouble(TxtCalc.Text);
            TxtCalc.Text = "";
        }

        private void BtnDevided_Click(object sender, EventArgs e)
        {
            sign = "/";
            firstno = Convert.ToDouble(TxtCalc.Text);
            TxtCalc.Text = "";

        }

        private void BtnPercent_Click(object sender, EventArgs e)
        {
            sign = "%";
            firstno = Convert.ToDouble(TxtCalc.Text);
            TxtCalc.Text = "";
        }

        private void BtnEquals_Click(object sender, EventArgs e)
        {
            double secno;
            double res = 0;                      //Initially result is zero(0)
            secno = Convert.ToDouble(TxtCalc.Text);       //convert value in textbox to double and put it in secno 
            if (sign == "+")
                res = firstno + secno;
            if (sign == "-")
                res = firstno - secno;
            if (sign == "*")
                res = firstno * secno;
            if (sign == "/")
                res = firstno / secno;
            if (sign == "*10")
                res = Math.Pow(firstno, secno);
            TxtCalc.Text = res.ToString();

        }

        private void BtnClear_Click(object sender, EventArgs e) //Reset button event
        {
            TxtCalc.Text = "";
        }

        private void button2_Click(object sender, EventArgs e) //Off click event
        {
            Application.Exit();           //used to exit application
        }

       
    }
}
                                                           OR


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        double opd1, opd2, res;
        string op;
        public Form2()
        {
            InitializeComponent();
        }
        private void Number_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Button Btn = sender as System.Windows.Forms.Button;
            TxtCalc.Text += Btn.Text;
        }
        private void Operator_Click(object sender, EventArgs e)
        {
            opd1 =Convert.ToDouble(TxtCalc.Text);
            System.Windows.Forms.Button Btn = sender as System.Windows.Forms.Button;
            op= Btn.Text;
            TxtCalc.Text = "";
        }
        private void BtnEquals_Click(object sender, EventArgs e)
        {
            opd2 = Convert.ToDouble(TxtCalc.Text);
            switch (op)
            {
                case "+":
                    res = opd1 + opd2;
                    break;
                case "-":
                    res = opd1 - opd2;
                    break;
                case "*":
                    res = opd1 * opd2;
                    break;
                case "/":
                    res = opd1 / opd2;
                    break;
            }
            TxtCalc.Text = res.ToString();
        }
        private void BtnClear_Click(object sender, EventArgs e)
        {
            TxtCalc.Text = "";
        }
    }
}
Note : You can add (Number_Click) in all Operator Click Event.
          You can add (Operator_Click) in all Operator Click Event.
How to add this event in all button Events.
    Just choose the button and press f4 after that just copy the event name and paste the click event. 

Tuesday, 16 April 2013

Second Question Show in listview




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        string cour;
        string gen;
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add("Name - "+TxtName.Text);
            listBox1.Items.Add("Roll No - "+TxtRoll.Text);
            //For Gender
            if(RadMale.Checked)
                gen=RadMale.Text;
            else
                gen=RadFemale.Text;
            listBox1.Items.Add("Gender - "+gen.ToString());
            //Gender work over
            ///==================
            //For Course
            if (ChkC.Checked)
                cour = ChkC.Text+",";
            if (ChkCPlus.Checked)
                cour += ChkCPlus.Text + ",";
            if (ChkJava.Checked)
                cour += ChkJava.Text;
            listBox1.Items.Add("Course - " + cour.ToString());
            //Course End
        }
      
    }
}

Calculation Part in checkcbox check





using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        private void Display()
        {
            int t = 0;
            if (Chk500.Checked)
                t += 500;
            if (Chk1000.Checked)
                t += 1000;
            if (Chk1500.Checked)
                t += 1500;
            TxtTotal.Text = t.ToString();
        }
        private void Chk500_CheckedChanged(object sender, EventArgs e)
        {
            Display();
        }

        private void Chk1000_CheckedChanged(object sender, EventArgs e)
        {
            Display();
        }

        private void Chk1500_CheckedChanged(object sender, EventArgs e)
        {
            Display();
        }
      
    }
}
Note :(+= )means It will add Previous Value and Current Value.

Wednesday, 3 April 2013

How to Upload file into Database and Display it using Gridview and Download the File


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">    
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Btn_Upload" runat="server" Text="Upload" OnClick="Btn_Upload_Click" />
        <asp:GridView ID="Grdvdetails" runat="server" AutoGenerateColumns="false" DataKeyNames="FilePath">
            <HeaderStyle BackColor="BlueViolet" />
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="ID" />
                <asp:BoundField DataField="FileName" HeaderText="FileName" />
                <asp:TemplateField HeaderStyle-BackColor="Chocolate">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkdownload" runat="server" Text="Download" OnClick="lnkdownload_Click"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

In the Code behind write the Following Code
------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;

public partial class DownloadUpload : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["cnstr"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            fillgridview();
        }
    }
    void fillgridview()
    {
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from Files", con);
        cmd.ExecuteNonQuery();
        SqlDataAdapter ad = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        ad.Fill(ds);
        con.Close();
        Grdvdetails.DataSource = ds;
        Grdvdetails.DataBind();


    }
    protected void Btn_Upload_Click(object sender, EventArgs e)
    {
        string filename = FileUpload1.PostedFile.FileName;
        FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Files/" + filename));

        con.Open();
        SqlCommand cmd = new SqlCommand("insert into Files(FileName,FilePath) values(@FileName,@FilePath)", con);
        cmd.Parameters.AddWithValue("@FileName", filename);
        cmd.Parameters.AddWithValue("@FilePath", "Files/" + filename);
        cmd.ExecuteNonQuery();
        fillgridview();
        con.Close();
    }
    protected void lnkdownload_Click(object sender, EventArgs e)
    {
        LinkButton lnk = sender as  LinkButton ;
        GridViewRow gvrow = (GridViewRow)lnk.NamingContainer;
        string filepath = Grdvdetails.DataKeys[gvrow.RowIndex].Value.ToString();
        Response.ContentType = "image/jpg";
        Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filepath + "\"");
        Response.TransmitFile(Server.MapPath(filepath));
        Response.End();

    }
}