Banner Ad

Showing posts with label CodeSnippets. Show all posts
Showing posts with label CodeSnippets. Show all posts

Monday, October 10, 2016

ASP.Net : Binding Dropdown in ASP.Net

By Francis   Posted at   7:55 PM   Dropdown Control in Asp.Net No comments
Binding dropdown is a common need in ASP.Net. The below code snippet is used to bind the datatable values to the dropdown list.

Markup:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:DropDownList runat="server" ID="ddlCity">
            </asp:DropDownList>
        </div>
    </form>
</body>
</html>

Code behind:

        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                //Substitute your DB and Server name below
                string conString = @"Data Source=Your_DBServer_Name;Initial Catalog=Your_DB_Name;Integrated Security=True";
                DataTable dtCity = new DataTable("City");
                // Create Connection and get the DB values
                using (SqlConnection connection= new SqlConnection(conString))
                {
                    SqlCommand command = new SqlCommand(conString,connection);
                    command.CommandText = "Select city_code,city_description from tblCity";
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    adapter.Fill(dtCity);
                }
                // Set the Datasource
                ddlCity.DataSource = dtCity;
                ddlCity.DataValueField = "city_code";
                ddlCity.DataTextField = "city_description";
                // Finally Bind it
                ddlCity.DataBind();
            }
        }

Wednesday, January 6, 2016

Replace Special character from string using Regular expression in C#

By Francis   Posted at   6:04 PM   CodeSnippets No comments
In one of the forum post, the poster asked to
  1. Remove all the special character
  2. Then Remove the space and replace with _ (underscore) character
Say for example, if he gave, the input string as “Levi Jeans (Blue) & yellow 101 – 150Ah” and the output he wants as “Levi_Jeans_Blue_yellow_101_150ah”.
Solution:

            string yourInput = "Levi Jeans (Blue) & yellow 101 - 150Ah"; 
            Regex rgx = new Regex(@"[^a-zA-Z\d\s]"); 
            // Replace Special Charater and space with emptystring 
            string finalOutput = rgx.Replace(yourInput,""); 
            Console.WriteLine(finalOutput); 
            Regex rgx1 = new Regex("\\s+"); 
            // Replace space with underscore 
            finalOutput = rgx1.Replace(finalOutput, "_");

Connect with Us