Follow us

Header Ads

Select Data From Database and Show Data in Lable in Asp.Net WebForm

 InsertDataIntoDropdownList.aspx

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:DropDownList ID="DropDownList1" runat="server" Height="16px" Width="183px">
            </asp:DropDownList>
            <br />
            <br />
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
        </div>
    </form>
</body>
</html>

 InsertDataIntoDropdownList.aspx.cs

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


public partial class InsertDataIntoDropdownList : System.Web.UI.Page
{
    string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            BindDropDownList();
        }

    }
    void BindDropDownList()
    {
        SqlConnection con = new SqlConnection(cs);
        string query = "select * from employee";
        SqlDataAdapter sda = new SqlDataAdapter(query, con);
        DataTable data = new DataTable();
        sda.Fill(data);
        DropDownList1.DataSource = data;
        //Nagar aayaga name par database me id jayga.
        DropDownList1.DataTextField = "name";
        DropDownList1.DataValueField = "id";
        DropDownList1.DataBind();
        //First item show hoga
        ListItem SelectItem = new ListItem("Select Employee","-1");
        SelectItem.Selected = true;
        DropDownList1.Items.Insert(0,SelectItem);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
      if(DropDownList1.SelectedValue=="-1")
        {
            Response.Write("Please select an employee");
        }
        else
        {
            Response.Write("Selected Item Text is:" + DropDownList1.SelectedItem.Text+"<br>");
            Response.Write("Selected Item Value is:" + DropDownList1.SelectedItem.Value + "<br>");
            Response.Write("Selected Item Index is:" + DropDownList1.SelectedIndex + "<br>");
        }
    }
}

Post a Comment

0 Comments