-->

Wednesday, December 30, 2015

Item add at first | 0 index After Bind ASP.NET DropDownList using c#

In this article, I will show you how to add item at 0 index after bind DropDownList in ASP.NET C#. I will give an simple example of it. First to bind the DropDownlist with the DataSource then you can use Insert method to add item at any position. Insert( ) method overloads with 4 parameters. You can use third option, in which we have two parameters first for Text and second for value.


Lets start to do:
Create a Database table with the following fields: 

CREATE TABLE [dbo].[user_table] (
    [Id]       INT           IDENTITY (1, 1) NOT NULL,
    [username] NVARCHAR (50) NULL,
    [Password] NVARCHAR (50) NULL,
    [email]    NVARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

1. Add a new web form in the project.
2. Bind it with the mentioned table using SqlDataReader class. 
3. After bind you can use insert method.

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default9 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            binddrop();

        }
    }

    private void binddrop()
    {
        //throw new NotImplementedException();
        SqlConnection con = new SqlConnection();
        con.ConnectionString=@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\emp.mdf;Integrated Security=True";
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "select * from [user_table]";
        cmd.Connection = con;
        SqlDataReader rd = cmd.ExecuteReader();
        DropDownList1.DataSource = rd;
        DropDownList1.DataTextField = "username";
        DropDownList1.DataValueField = "Id";
        DropDownList1.DataBind();
        DropDownList1.Items.Insert(0, new ListItem("Apple","5"));

    }
}

Tuesday, December 29, 2015

ASP.NET RSS Feeds Display | Get

In this article, I will show you, How to display RSS feeds on your website. Actually, RSS feeds is an XML file. In ASP.NET we can create it easily through generic handlers. By using XmlTextWriter class, we can create XML file and XmlTextReader class we can read XML file. In this article, I will use XmlTextReader class to read it.


Complete Source Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReadRss.aspx.cs" Inherits="ReadRss" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Read Rss" OnClick="Button1_Click" Width="163px" />
    </div>
        <asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>
                <table>
                    <tr>
                        <td>
                            <asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("Title")%>'/>


                        </td>
                    </tr>
                     <tr>
                        <td>
                            <asp:Label ID="Label1" runat="server" Text='<%# Eval("Description") %>'/>


                        </td>
                    </tr>
                </table>


            </ItemTemplate>
        </asp:Repeater>
    </form>
</body>
</html>

CodeBehind File

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

public partial class ReadRss : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        WebRequest request = WebRequest.Create("http://localhost:11973/Handler.ashx");
        WebProxy proxy = new WebProxy("http://localhost:11973/Handler.ashx", true);
        request.Proxy = proxy;
        request.Timeout = 6000;
        try
        {
            WebResponse response = request.GetResponse();
            XmlTextReader xmlreader = new XmlTextReader(response.GetResponseStream());
            DataSet ds = new DataSet();
            ds.ReadXml(xmlreader);
            Repeater1.DataSource = ds.Tables[2];
            Repeater1.DataBind();
        }
       catch(Exception ex)
        {
            throw ex;
        }
    }
}

ASP.NET : How to use image in error message in validation Control

If you are generating error  message to the client side then you can use any type of validation in given ToolBox such as RequiredField validator , compare validator , custom validator etc. If you want to use Image for easy understand then you should insert image in Text property of the validation control.

 <asp:RequiredFieldValidator  ControlToValidate ="TextBox1" Text="<img width='40px' height='40px' src='error.jpg' />" ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>


Here we have used HTML Image Tag inside Text property of control.
Example
<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:TextBox ID="TextBox1" runat="server" Width="201px"></asp:TextBox>
        <asp:RequiredFieldValidator  ControlToValidate ="TextBox1" Text="<img width='40px' height='40px' src='error.jpg' />" ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>

        <asp:Button ID="Button1" runat="server" Text="Check RequiredField" />
    </div>
    </form>
</body>
</html>


Output
ASP.NET : How to use image in error message in validation Control

Monday, December 28, 2015

ASP.NET Rss Feeds Create Database Table

In this Article, I will show you, How to create Rss feeds for your website article. Rss feed is a xml file so in this article, i will create a XML file and Data pick from database table. Rss contains differenet filds link channel , article title, article description, link of the article and many more things. By using Rss feeds we can improve our search engine results , i mean to say we can improve our SEO of the website. 

How to Start it: First of all create two table in the database, These are the fields which are mentioned below. If you are the beginners then i will provide you a short video through this you can create both table easily. 



Also i will provide you scripts of table, through these you can directly create table into your database.

CREATE TABLE [dbo].[Channel] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [Title]       NVARCHAR (100) NULL,
    [Description] NVARCHAR (MAX) NULL,
    [Link]        NVARCHAR (100) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);


CREATE TABLE [dbo].[Feeds] (
    [Id]          UNIQUEIDENTIFIER NOT NULL,
    [ChannelID]   INT              IDENTITY (1, 1) NOT NULL,
    [Title]       NVARCHAR (100)   NULL,
    [Description] NVARCHAR (MAX)   NULL,
    [Link]        NVARCHAR (100)   NULL,
    [PDate]       NVARCHAR (100)   NULL,
    PRIMARY KEY CLUSTERED ([ChannelID] ASC)
);




Add a Generic handler file, In it you have a ProcessRequest method. In This method you have to create your logic , I mean to say put your business logic code. You can copy the mentioned code and paste into your Generic Handler file.

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Xml;
using System.Data;
using System.Data.SqlClient;

public class Handler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        createFeed(context, 1);
    }
    private void createFeed(HttpContext context,int chnlID)
    {
        using (XmlTextWriter writer=new XmlTextWriter(context.Response.OutputStream,System.Text.Encoding.UTF8))
        {
            DataTable dtable = GetTable("select * from [Channel] where Id=@channelID", chnlID);
            writer.WriteStartDocument();
            writer.WriteStartElement("Rss");
            writer.WriteAttributeString("version", "1.0");
            writer.WriteStartElement("Channel");
            writer.WriteElementString("Title", dtable.Rows[0]["Title"].ToString());
            writer.WriteElementString("Description", dtable.Rows[0]["Description"].ToString());
            writer.WriteElementString("Link", dtable.Rows[0]["Link"].ToString());
            //writer.WriteElementString("Title", dtable.Rows[0]["Title"].ToString());


            dtable = GetTable("select * from [Feeds] where ChannelID= @channelID", chnlID);
            foreach (DataRow item in dtable.Rows)
            {
                writer.WriteStartElement("Item");
                writer.WriteElementString("Title", item["Title"].ToString());
                writer.WriteElementString("Description", item["Description"].ToString());
                writer.WriteElementString("Link", item["Link"].ToString());
                writer.WriteElementString("Pub-Date", item["PDate"].ToString());
                writer.WriteElementString("UniqueId",item["Id"].ToString());
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Flush();
            writer.Close();
         
         
         
        }
    }
    private DataTable GetTable(string qry,int chnlID)
    {
        DataTable dt=new DataTable();
        SqlConnection con = new SqlConnection();
        con.ConnectionString=@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True";
        con.Open();
        SqlCommand cmd = new SqlCommand(qry, con);
        cmd.Parameters.AddWithValue("@channelID", chnlID);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        return dt;        
     
     
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

Saturday, December 26, 2015

How to change forecolor and backcolor dynamically of dropdownlist in ASP.NET

ForeColor and BackColor Change Dynamically

Using the color property you can change your appearance of the Control. Looks is matter for any website if you do something different for your visitor or registered user. Your website visitor want that no one text hidden on the website.
ForeColor : This is the TextColor which is appear in the DropDownlist .
BackColor : This is the BackGround color.
Example of the dynamically change forecolor and backcolor


<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, EventArgs e)
    {
        DropDownList1.ForeColor = System.Drawing.Color.White;
 
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        DropDownList1.BackColor = System.Drawing.Color.Black;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .auto-style1 {
            font-size: large;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <span class="auto-style1"><strong>Change Fore color and backcolor of the dropdownlist
        <br />
        </strong>
        <asp:DropDownList ID="DropDownList1" runat="server" Height="34px" Width="157px">
            <asp:ListItem>Apple </asp:ListItem>
            <asp:ListItem>Mango</asp:ListItem>
            <asp:ListItem>Orange</asp:ListItem>
        </asp:DropDownList>
        <br />
        <br />
        </span>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Change fore color" Width="112px" />
        <br />
        <br />
        <asp:Button ID="Button2" runat="server" Text="Change back color" Width="112px" OnClick="Button2_Click" />
        <br />

    </div>
    </form>
</body>
</html>


Output
How to change forecolor and backcolor dynamically of dropdownlist in ASP.NET

Friday, December 25, 2015

Solve Application not responding problem

In this article, I will show you how to fix computer hanging problems. Generally, we all know about "Not Responding" problem. When processor takes time to execute the process then thats type of problem occurs. By using this article, I will resolve this issue.




Windows Form Design:

Solve Application not responding problem
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication5
{
    public partial class Form1 : Form
    {
        private readonly SynchronizationContext synchronizationContext;
        private DateTime previousTime = DateTime.Now;
        public Form1()
        {
            InitializeComponent();
            synchronizationContext = SynchronizationContext.Current;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (var i = 0; i <= 1000000; i++)
            {
                label1.Text = @"Count : " + i;
            }
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            button2.Enabled = false;
            var count = 0;

            await Task.Run(() =>
            {
                for (var i = 0; i <= 1000000; i++)
                {
                    UpdateUI(i);
                    count = i;
                }
            });
            label1.Text = @"Count : " + count;
            button1.Enabled = true;
            button1.Enabled = false;
        }
        public void UpdateUI(int value)
        {
            var timeNow = DateTime.Now;

            //Here we only refresh our UI each 50 ms
            if ((DateTime.Now - previousTime).Milliseconds <= 50) return;

            //Send the update to our UI thread
            synchronizationContext.Post(new SendOrPostCallback(o =>
            {
                label1.Text = @"Count : " + (int)o;
            }), value);

            previousTime = timeNow;
        }
    }
}

How to bind Bulleted List control in asp.net

Following some steps for binding bulleted list control using SqlDataSource

In this article, I will show you, How to bind BulletedList in ASP.NET. In this article, I will take SQL DataSource control to bind it. ASP.NET Provide inbuilt control to bind any other control like ListBox, ComboBox, BulletedList. After bind it, it will look like list of unordered list of HTML.Lets  to Start how to bind it. I will Give you, video as well as code for this.




Step-1 : Open visual studio
Step-2:  Click  File-->New-->WebSite
starting screen

Step-3: Right click on website name in solution explorer, Add-->Add new item 

web form


Step-4: Make Database table 
Step-5: Drag Bulleted list from toolbox and drop on design window.
Step-6: Select Show smart tag of Bulleted list
show smart tag

Step-7: On Bulledted list task click choose data source link
Step-8: Select New DataSource from Data Source configuration wizard.

choose data source

Step-9: Select SQL Database from Data Source Configuration wizard. and click ok button

data configuration wizard

Step-10 : Select existing database from configure data source.

connection string property

Step-11 : Change Connection name according to you and click ok
web.config file

Step-12 : Select table from name ,select table field name and press ok button

table view

Step-13: Click test query button and finish the process
Step-14: Select a data field to display in the bulleted list.
Step-15: Select a data field for the value of the bulleted list. and press ok button
select one those field in bulleted list

Run your application
how to bind bulleted list in asp.net

Finally source of the code are:



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:BulletedList ID="BulletedList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="Name " DataValueField="Url">
        </asp:BulletedList>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [mytab]"></asp:SqlDataSource>
    
    </div>
    </form>
</body>
</html>
Top Related Article

© Copyright 2013 Computer Programming | All Right Reserved