Monday, May 26, 2014

Coding tricks in .net part 01

In this post i'm going to discuss some of the tricks in .net application that I've used.to avoid unnecessary code lines , defensive programming are the required talent of the programmer.

1)Error handling with showing message
always write your code starting point within try catch block. eg. only for raise it event root (button click event)
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtName.Text.Trim().Length == 0)
                {
                    MessageBox.Show("Name is required");
                    return;
                }
                /// do some coding here
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error");
            }
        }.
above code is nothing wrong, but it used unnecessary return statements.
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtName.Text.Trim().Length == 0)
                {
                    throw new ApplicationException("Name is required");
                }
                /// do some coding here
            }
            catch (ApplicationException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error");
            }
        }
Application level errors is captured by ApplicationException class.there're no any return and more clear and specific.

2) Windows application Stores object in textbox (suppose you want to display Employee name in text box and also required to hide Employee id form the screen.one textbox for employee and lable for empid which is invisible)
in Textbox has property called Tag , that can hold required data invisibly.
            Employee emp = new Employee() { ID = 11, Name = "NImal" };
            //Assing
            txtName.Text = emp.Name;
            txtName.Tag = emp;//obj is employee related data eg.ID,DateJoind etc

            //retrive
            Employee empObje =(Employee) txtName.Tag;

////////////////////////////////////
    public class Employee
    {
        public string Name { get; set; }
        public int ID { get; set; }

    }

3) add rows to DataGridView
           int i= dataGridView1.Rows.Add();
           dataGridView1.Rows[i].Cells["Column1"].Value = 22;

           dataGridView1.Rows[i].Cells["Column2"].Value = "SSS";
above code is to add new row to datagridview (which has 2 columns).nothing wrong it.what will happen if column names are changed.code will be complied at run time will be caused an error .because column names are not strongly type. dataGridView1.Rows is duplication among the code.to alternative this issue , here code snippet.

           DataGridViewRow gr =dataGridView1.Rows[dataGridView1.Rows.Add()];
           gr.Cells[Column1.Name].Value = 22;

           gr.Cells[Column2.Name].Value = "SSS";

4)strongly type session and viewstate (asp.net)
in asp.net application we stored data as globally (session) and page level (view state).
eg. Session["abc"]=1500;
      ViewState["aa"]="xx";
these are not strongly types ,only accept object and we have cast it before use it.
        //Session
        public int sEmpID
        {
            get {
                if ((Session["empID"] == null))
                {
                    return 0;//throw new applicationException("Session expired");
                }
                else
                {
                    return Convert.ToInt16(Session["empID"]);
                }
            }
            set { Session["empID"] = value; }
        }

        //ViewState
        public bool vsIsEdit
        {
            get { return Convert.ToBoolean(ViewState["IsEdit"]); }
                               set { ViewState["IsEdit"] = value; }
        }

/////////////// assign values
            sEmpID = 22;


            vsIsEdit = true;

happy coding.........

No comments:

Post a Comment