Translate

ASP.NET C# Popup MessageBox

Tuesday, June 26, 2012 Category : , 1

 public static void ShowAlertMessage(string error)
        {
            Page page = HttpContext.Current.Handler as Page;
            if (page != null)
            {
                error = error.Replace("'", "\'");

                ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + error + "');", true);
            }
        }

ASP.NET Regular Expressions List

Category : 0

Expression List :
Minimum 3 Character Validation :    ^[a-zA-Z0-9]{3,}

Only 6 Numbers allowed :    [0-9]{6,}

Only Numbers Allowed :    ^\d+$

Date Validator : ^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$  (dd/MM/yyyy)        (dd/mm/yyyy)

Date Validator :  ^([0-9]{1,2})[./-]+([0-9]{1,2})[./-]+([0-9]{2}|[0-9]{4})$       (mm/dd/yyyy)

Mail Validator  :  

"^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$"

C# Problem With Inserting more than 3000 data in Database

Tuesday, June 19, 2012 Category : 0

// some time a problem arises when user perfrom some loop operation which perfrm more than
//3000 thousand calculation and some time CLR stop the process. in this case you need to use thread

private Thread demoThread = null;

 private void btnBrowse_Click(object sender, EventArgs e)
 {
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                                   this.demoThread = new Thread(new ThreadStart(InsertData));
                                   this.demoThread.Start();
                 // OR
                //ThreadPool.QueueUserWorkItem(new WaitCallback(InsertData), oChalanObject); 
            }
}

// note here InserData is a function which perfrom a insert operation. you can use thread in this two
//way second option is if u want to pass a parameter in Function .


 private void InsertData()
 {
        // write your code here
// note you can not access any winform control directyly if want to access a TextBox or Combobox or //something else then you need a delegate to perform this operation. for example
SetControlPropertyValue(lblProgress, "Text", value);
ClearGroupBoxContent(groupBox1);
}



// Generic Control Value Seter function
delegate void SetControlValueCallback(Control oControl, string propName, object propValue);
        private void SetControlPropertyValue(Control oControl, string propName, object propValue)
        {
            try
            {
                if (oControl.InvokeRequired)
                {
                    SetControlValueCallback d = new SetControlValueCallback(SetControlPropertyValue);
                    oControl.Invoke(d, new object[] { oControl, propName, propValue });
                }
                else
                {
                    Type t = oControl.GetType();
                    PropertyInfo[] props = t.GetProperties();
                    foreach (PropertyInfo p in props)
                    {
                        if (p.Name.ToUpper() == propName.ToUpper())
                        {
                            p.SetValue(oControl, propValue, null);
                        }
                    }
                }
            }
            catch (Exception)
            {

            }
        }

// only a specific Control Property set
delegate void GroupBoxPerformStep(GroupBox group1);
        private void ClearGroupBoxContent(GroupBox group1)
        {
            if (group1.InvokeRequired)
            {
                GroupBoxPerformStep del = ClearGroupBoxContent;
                group1.Invoke(del, new object[] { group1 });
                return;
            }
            Result oResult = new Result();
            oResult.ClearAll(group1);
            //myProgressBar.PerformStep();

        }

C# Thread Handleing in Winform

Category : 0

private Thread demoThread = null;

 private void btnBrowse_Click(object sender, EventArgs e)
 {
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                                   this.demoThread = new Thread(new ThreadStart(InsertData));
                                   this.demoThread.Start();
                 // OR
                //ThreadPool.QueueUserWorkItem(new WaitCallback(InsertData), oChalanObject); 
            }
}

// note here InserData is a function which perfrom a insert operation. you can use thread in this two
//way second option is if u want to pass a parameter in Function .


 private void InsertData()
 {
        // write your code here
// note you can not access any winform control directyly if want to access a TextBox or Combobox or //something else then you need a delegate to perform this operation. for example
SetControlPropertyValue(lblProgress, "Text", value);
ClearGroupBoxContent(groupBox1);
}



// Generic Control Value Seter function
delegate void SetControlValueCallback(Control oControl, string propName, object propValue);
        private void SetControlPropertyValue(Control oControl, string propName, object propValue)
        {
            try
            {
                if (oControl.InvokeRequired)
                {
                    SetControlValueCallback d = new SetControlValueCallback(SetControlPropertyValue);
                    oControl.Invoke(d, new object[] { oControl, propName, propValue });
                }
                else
                {
                    Type t = oControl.GetType();
                    PropertyInfo[] props = t.GetProperties();
                    foreach (PropertyInfo p in props)
                    {
                        if (p.Name.ToUpper() == propName.ToUpper())
                        {
                            p.SetValue(oControl, propValue, null);
                        }
                    }
                }
            }
            catch (Exception)
            {

            }
        }

// only a specific Control Property set
delegate void GroupBoxPerformStep(GroupBox group1);
        private void ClearGroupBoxContent(GroupBox group1)
        {
            if (group1.InvokeRequired)
            {
                GroupBoxPerformStep del = ClearGroupBoxContent;
                group1.Invoke(del, new object[] { group1 });
                return;
            }
            Result oResult = new Result();
            oResult.ClearAll(group1);
            //myProgressBar.PerformStep();

        }

C# Read Excel (xls,xlsx) File

Friday, June 1, 2012 Category : 1

  public DataTable SelectAll(string FilePath, string Extension, string isHDR)
        {

            string conStr = "";

            switch (Extension)
            {

                case ".xls": //Excel 97-03

                    conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties='Excel 8.0;HDR={1}'";

                    break;

                case ".xlsx": //Excel 07

                    conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";

                    break;

            }

            conStr = String.Format(conStr, FilePath, isHDR);

            OleDbConnection connExcel = new OleDbConnection(conStr);

            OleDbCommand cmdExcel = new OleDbCommand();

            OleDbDataAdapter oda = new OleDbDataAdapter();

            DataTable dt = new DataTable();

            cmdExcel.Connection = connExcel;



            //Get the name of First Sheet

            connExcel.Open();

            DataTable dtExcelSchema;

            dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

            string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();

            connExcel.Close();



            //Read Data from First Sheet

            connExcel.Open();

            cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";

            oda.SelectCommand = cmdExcel;

            oda.Fill(dt);

            connExcel.Close();



            return dt;



        }


ASP.NET GridView Row Delete Confirmation

Tuesday, May 29, 2012 Category : 0

 <asp:TemplateField>
                <ItemTemplate>
                <asp:LinkButton Runat="server" CommandName="Edit">Edit</asp:LinkButton>
           <asp:LinkButton Runat="server" CausesValidation="False"
               OnClientClick="return confirm('Are you sure you want to delete this distribution?');"
               CommandName="Delete">Delete</asp:LinkButton>
       </ItemTemplate>
       <EditItemTemplate>  
           <asp:LinkButton CommandName="Update" Text="Update"    
               runat="server"/>    
           <asp:LinkButton CommandName="Cancel" Text="Cancel"
               runat="server"/>          
       </EditItemTemplate>
 </asp:TemplateField>

ASP.NET GridView with Combobox ObjectDataSource EasyUpdate

Sunday, May 20, 2012 Category : 0



BLL CLass For Data Insert

namespace SampleASP.Model
{
    [DataObject]
    public class Client
    {

        public string ID { get; set; }

        public string UserName { get; set; }

        public string Address { get; set; }
        public string AdminUserID { get; set; }
        public string AdminUserName { get; set; }
       
        private Result obResult = new Result();
        private DALS obDAL = new DALS();

        [DataObjectMethod(DataObjectMethodType.Insert)]
        public Result Save(Client obClients)
        {
            string query = @"INSERT INTO Client([id],[name],[address],[userID])   VALUES   (" + obClients.ID + ",'" + obClients.UserName + "', '" + obClients.Address + "','" + obClients.AdminUserID + "')";
            obResult = obDAL.Create(query);
            return obResult;       
        }

        [DataObjectMethod(DataObjectMethodType.Select)]
        public List<Client> SelectAll()
        {
            List<Client> obCLientList = new List<Client>();
            string query = "Select * from Client";
            obResult = obDAL.Select(query);
            DataTable dt = obResult.Data as DataTable;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Client obClient = new Client();
                obClient.ID = dt.Rows[i]["id"].ToString();
                obClient.UserName = dt.Rows[i]["name"].ToString();
                obClient.Address = dt.Rows[i]["address"].ToString();
                obClient.AdminUserID = dt.Rows[i]["userID"].ToString();
                obCLientList.Add(obClient);

            }
            return obCLientList;
        }

        [DataObjectMethod(DataObjectMethodType.Update)]
        public int Update(Client obClients)
        {
            string query = "UPDATE Client set name='" + obClients.UserName + "', address='" + obClients.Address + "',userID='" + obClients.AdminUserID + "' where id=" + obClients.ID;
            obResult = obDAL.Update(query);
            if (obResult.ResultState)
            {
                return 1;
            }
            return 0;
        }

        [DataObjectMethod(DataObjectMethodType.Delete)]
        public int Delete(Client obClients)
        {
            string query = "DELETE FROM Client where id="+ obClients.ID;
            obResult = obDAL.Update(query);
            if (obResult.ResultState)
            {
                return 1;
            }
            return 0;
        }

    }

ASPX GRID CODE

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
        AutoGenerateColumns="False" DataSourceID="ObjectDataSource2"
        DataKeyNames="id" onrowdatabound="GridView1_RowDataBound"
        onrowupdating="GridView1_RowUpdating">
        <Columns>
            <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
            <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" ReadOnly="true" />
            <asp:BoundField DataField="UserName" HeaderText="UserName"
                SortExpression="UserName" />
            <asp:BoundField DataField="Address" HeaderText="Address"
                SortExpression="Address" />
           
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:DropDownList ID="DropDownList1" runat="server"
                        DataSourceID="ObjectDataSource1" DataTextField="UserName" DataValueField="AdminUserID" SelectedValue='<%# Eval("AdminUserID") %>' >
                    </asp:DropDownList>
                    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
                        OldValuesParameterFormatString="original_{0}" SelectMethod="SelectAll"
                        TypeName="SampleASP.Model.Users"></asp:ObjectDataSource>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <asp:ObjectDataSource ID="ObjectDataSource2" runat="server"
        DataObjectTypeName="SampleASP.Model.Client" DeleteMethod="Delete"
        OldValuesParameterFormatString="original_{0}" SelectMethod="SelectAll"
        TypeName="SampleASP.Model.Client" UpdateMethod="Update"
        onupdated="ObjectDataSource2_Updated"
        onupdating="ObjectDataSource2_Updating">
        <UpdateParameters>
            <asp:ControlParameter ControlID="DropDownList1" Name="AdminUserID" Type="String" />
        </UpdateParameters>
    </asp:ObjectDataSource>


CodeBehid File Code

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            DropDownList ddl = GridView1.Rows[e.RowIndex].FindControl("DropDownList1") as DropDownList;
            e.NewValues["AdminUserID"] = ddl.SelectedValue.ToString();
        } 


 

Powered by Blogger.