Tuesday, 11 December 2012

conditional execution of two classes in c#

Below code is the best solution when, developer wish to execute 2nd class, only if 1st class  get executed successfully

Class 1st


public bool SaveOtherInfo()
        {
            try
            {
                con.Open();
                if (textBoxSrNo.Text == "" || textBoxCARD2.Text == "" || textBoxFirstName.Text == "")
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('One or more field are empty..');", true);
                    return false;
                }
                if (FileUpload1.FileName == "")
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Select Image');", true);
                    return false;
                }
                else
                {
                    param = " '" + this.textBoxSrNo.Text + "' ," +   
                            " '" + this.comboBoxRelocate.Text + " '";


                    strSQL = @"INSERT  INTO student VALUES (" + param + ")";

                    cmd.Connection = con;
                    cmd.CommandText = strSQL;
                    cmd.CommandType = CommandType.Text;

                    int i = cmd.ExecuteNonQuery();


                    if (i > 0)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Information submitted Successfully');", true);
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + ex.Message + "');", true);
                return false;
            }
            finally
            {
                con.Close();
            }
            return true;
        }


Class 2nd

private bool SaveImage()
        {
            try
            {
                //Condition to check if the file uploaded or not
                if (FileUpload1.HasFile)
                {
                    //getting length of uploaded file
                    int length = FileUpload1.PostedFile.ContentLength;

                    //create a byte array to store the binary image data
                    byte[] imgbyte = new byte[length];

                    //store the currently selected file in memeory
                    HttpPostedFile img = FileUpload1.PostedFile;

                    //set the binary data
                    img.InputStream.Read(imgbyte, 0, length);
                    con.Open();

                    SqlCommand cmd = new SqlCommand("INSERT INTO ImageTable VALUES(@srno,@image)", con);
                    cmd.Parameters.Add("@srno", SqlDbType.NVarChar, 50).Value = textBoxSrNo.Text;
                    cmd.Parameters.Add("@image", SqlDbType.Image).Value = imgbyte;

                    int count = cmd.ExecuteNonQuery();
                    con.Close();
                    if (count > 0)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Image Inserted Successfully');", true);

                    }
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + ex.Message + "');", true);
                return false;
            }
            finally
            {

            }
            return true;

        }

Button for checking classes execution and save data of both the classes if both classes executes successfully,

In short, If class"SaveOtherInfo" gets executed successfully then only class"SaveImage" get executed otherwise not..


protected void ButtonSave_Click(object sender, EventArgs e)
        {
            bool flag;
            flag = SaveOtherInfo();

            if (flag == true)
            {
                SaveImage();
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Can not Insert Data');", true);
            }
        }


display two columns combobox c#

display two columns combobox c#


con.Open();
OleDbCommand cmd = new OleDbCommand("Select emaployeeFirstName + ' ' + employeeLastName as name from Employee", con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
comboBoxLabour.DisplayMember = "name";
comboBoxLabour.ValueMember = "name";
comboBoxLabour.DataSource = dt;
con.Close();

Wednesday, 5 December 2012

Passing label value to crystal report text object in c# windows application



 private void buttonFinish_Click(object sender, EventArgs e)
        {
            string FromMonth = comboBoxFromMonth.Text, FromYear= comboBoxFromYear.Text, ToMonth= comboBoxToMonth.Text, ToYear=comboBoxToYear.Text;
            Form6 frm = new Form6(FromMonth,FromYear,ToMonth,ToYear);
            frm.MdiParent = this.MdiParent;
            frm.Dock = DockStyle.Fill;
            frm.Show();
        }














Form 6: code behind

public Form6(string FromMonth, string FromYear, string ToMonth, string ToYear)
        {
            InitializeComponent();
            label1.Text = FromMonth;
            label2.Text = FromYear;
            label3.Text = ToMonth;
            label4.Text = ToYear;
        }

 private void Form6_Load(object sender, EventArgs e)
        {
            crystalReportViewer1.DisplayGroupTree = false;
        }

private void crystalReportViewer1_Load(object sender, EventArgs e)
        {
            ParameterFieldDefinitions crParameterFieldDefinitions;
            ParameterFieldDefinition crParameterFieldDefinition;
            ParameterValues crParameterValues = new ParameterValues();
            ParameterDiscreteValue crParameterDiscreteValue = new ParameterDiscreteValue();

            CrystalReport6 myreport;
            string selectSQL = null;
            selectSQL = "Select * from salaryslip where [year] between '" + label2.Text + "'AND '" + label4.Text + "' AND [month] between '" + label1.Text + "'AND'" + label3.Text + "'";
            con.Open();
            DataSet6 ds = new DataSet6();
            OleDbCommand cmd = new OleDbCommand(selectSQL, con);
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            da.Fill(ds, "salaryslip");
            myreport = new CrystalReport6();
            myreport.SetDataSource(ds);
            crystalReportViewer1.ReportSource = myreport;

            crParameterDiscreteValue.Value = label1.Text;
            crParameterFieldDefinitions = myreport.DataDefinition.ParameterFields;
            crParameterFieldDefinition = crParameterFieldDefinitions["FromMonth"];
            crParameterValues = crParameterFieldDefinition.CurrentValues;

            crParameterValues.Clear();
            crParameterValues.Add(crParameterDiscreteValue);
            crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

            crParameterDiscreteValue.Value = label2.Text;
            crParameterFieldDefinitions = myreport.DataDefinition.ParameterFields;
            crParameterFieldDefinition = crParameterFieldDefinitions["FromYear"];
            crParameterValues = crParameterFieldDefinition.CurrentValues;

            crParameterValues.Clear();
            crParameterValues.Add(crParameterDiscreteValue);
            crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

            crParameterDiscreteValue.Value = label3.Text;
            crParameterFieldDefinitions = myreport.DataDefinition.ParameterFields;
            crParameterFieldDefinition = crParameterFieldDefinitions["ToMonth"];
            crParameterValues = crParameterFieldDefinition.CurrentValues;

            crParameterValues.Clear();
            crParameterValues.Add(crParameterDiscreteValue);
            crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

            crParameterDiscreteValue.Value = label4.Text;
            crParameterFieldDefinitions = myreport.DataDefinition.ParameterFields;
            crParameterFieldDefinition = crParameterFieldDefinitions["ToYear"];
            crParameterValues = crParameterFieldDefinition.CurrentValues;

            crParameterValues.Clear();
            crParameterValues.Add(crParameterDiscreteValue);
            crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

            da.Dispose();
            con.Close();
        }

Monday, 26 November 2012

how to bind data to listview in c#.net

             InitializeComponent();

            // Set the view to show details.
            lvwResult.View = View.Details;

            // Allow the user to edit item text.
            lvwResult.LabelEdit = true;

            // Allow the user to rearrange columns.
            lvwResult.AllowColumnReorder = true;

            // Select the item and subitems when selection is made.
            lvwResult.FullRowSelect = true;

            // Display grid lines.
            lvwResult.GridLines = true;

            // Sort the items in the list in ascending order.
            lvwResult.Sorting = SortOrder.Ascending;


private void Form_Load()
        {
            lvwResult.Columns.Clear();
            lvwResult.Items.Clear();
            lvwResult.View = View.Details;
            lvwResult.LabelEdit = true;
            lvwResult.Columns.Add("Company ID", 100, HorizontalAlignment.Center);
            lvwResult.Columns.Add("Company Name", 150, HorizontalAlignment.Center);
            lvwResult.Columns.Add("Company Website", 150, HorizontalAlignment.Center);
            lvwResult.Columns.Add("Company Email", 150, HorizontalAlignment.Center);
            con.Open();
            lvwResult.Items.Clear();
            lvwResult.Refresh();
            string OleDb = "select * from Company";
            OleDbCommand cmd = new OleDbCommand(OleDb, con);
            OleDbDataAdapter dap = new OleDbDataAdapter(cmd);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            DataTable dt = ds.Tables[0];

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                ListViewItem lvi = new ListViewItem(dr["companyID"].ToString());
                lvi.SubItems.Add(dr["companyName"].ToString());
                lvi.SubItems.Add(dr["companyWebsite"].ToString());
                lvi.SubItems.Add(dr["companyEmail"].ToString());
                lvwResult.Items.Add(lvi);
                lvwResult.FullRowSelect = true;

            }
            con.Close();
        }



private void lvwResult_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvwResult.SelectedItems.Count > 0)
            {
                textBox1.Text = lvwResult.SelectedItems[0].Text;
            }

            ViewCompanyDetails objViewCompanyDetails = new ViewCompanyDetails(textBox1.Text);
            objViewCompanyDetails.MdiParent = this.MdiParent;
            objViewCompanyDetails.Dock = DockStyle.Fill;
            objViewCompanyDetails.Show();
            objViewCompanyDetails.Focus();
            this.Hide();
        }

connection state giving problem

if (dbConnection.State != ConnectionState.Open)
        dbConnection.Open();

how to bind combobox with datatable in c#

con.Open();
            cmd = new OleDbCommand("Select DISTINCT departmentName from Department", con);
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            comboBoxDepartment.DisplayMember = "departmentName";
            comboBoxDepartment.ValueMember = "departmentName";
            comboBoxDepartment.DataSource = dt;
            con.Close();

export dataset to excel in c# windows application

Export Data in excel sheet from DataGridView C# Windows Application

Microsoft.Office.Interop.Excel.Application ExcelApp =
            new Microsoft.Office.Interop.Excel.Application();
            ExcelApp.Application.Workbooks.Add(Type.Missing);

            // Change properties of the Workbook

            ExcelApp.Columns.ColumnWidth = 20;

            // Storing header part in Excel
            for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
            {
                ExcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
            }

            // Storing Each row and column value to excel sheet
            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    ExcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                }
            }
            MessageBox.Show("Excel file created , you can find the file D:\\Employee Data.xlsx");
            ExcelApp.Visible = true;
            ExcelApp.ActiveWorkbook.SaveCopyAs("D:\\Employee Data.xlsx");
            ExcelApp.ActiveWorkbook.Saved = true;
           
            //ExcelApp.Quit();