First Item on Dropdownlist in blank - asp.net

How to put the first item on the DropDownList in blank ? In VB is something like, DropDownList.index[0] = "";
I did this:
string StrConn = ConfigurationManager.ConnectionStrings["connSql"].ConnectionString;
SqlConnection conn = new SqlConnection(StrConn);
conn.Open();
SqlDataReader dr;
string sql;
sql = #"Select Nome From DanielPessoas";
SqlCommand cmd = new SqlCommand(sql, conn);
dr = cmd.ExecuteReader();
DropDownList1.DataSource = dr;
DropDownList1.DataTextField = "Nome";
DropDownList1.DataValueField = "Nome";
DropDownList1.DataBind();

After your DataBind call, add this code.
DropDownList1.Items.Insert(0, new ListItem(string.Empty, string.Empty));

You can define the empty item in aspx file if you set AppendDataBoundItems property to true.
<asp:DropDownList ID="ddlPersons" runat="server" AppendDataBoundItems="true" DataValueField="ID" DataTextField="Name">
<asp:ListItem> -- please select person -- </asp:ListItem>
</asp:DropDownList>
Then you can databind items from the database in the codebehind:
ddlPersons.DataSource = personsList;
ddlPersons.DataBind();
I regard this "empty item" as presentation / UI, so I like to put it in the aspx. It also keeps the codebehind simpler.

Do something like this: Here is a simple example
<asp:DropDownList ID="ddlFruits" runat="server">
<asp:ListItem Value="1" Text="Oranges"></asp:ListItem>
<asp:ListItem Value="2" Text="Apples"></asp:ListItem>
<asp:ListItem Value="3" Text="Grapes"></asp:ListItem>
<asp:ListItem Value="4" Text="Mangoes"></asp:ListItem>
</asp:DropDownList>
And in the code behind
ddlFruits.Items.Insert(0, new ListItem(string.Empty, "0"));

You can do it with this way:
dropdownlist1.Items.Insert(0, new ListItem("Select here...", string.Empty));

You can do it in SQL:
sql = #"Select Nome From DanielPessoas UNION ALL Select '' Order by Nome";

We can do this on the front end in C#
#Html.DropDownList("sample",new SelectList(DropDownList1, "DataTextField", "DataValueField "), "Select")

Related

Dropdown List selected value display only one using Asp.net

i have load the DropDownList successfully. all student numbers i have loaded when i select the student no relavent student name should diplay on the below textbox. but now if select any number only one student name is shown John name only. if i select diffent student numbers. i don't know why.
DropDownList Load code
string cmdstr = "select id from records";
SqlCommand cmd = new SqlCommand(cmdstr, con);
con.Open();
read = cmd.ExecuteReader();
DropDownList1.Items.Clear();
while (read.Read())
{
DropDownList1.Items.Add(read["id"].ToString());
}
con.Close();
Selected data
<asp:DropDownList ID="DropDownList1" ViewStateMode="Enabled" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList>
if (Page.IsPostBack == true)
{
string cmdstr = "select firstname from records where id = " +
DropDownList1.SelectedValue;
SqlCommand cmd = new SqlCommand(cmdstr, con);
con.Open();
read = cmd.ExecuteReader();
while (read.Read())
{
name.Text = read["firstname"].ToString();
}
con.Close();
}
I have a example: evt. this helps
<asp:DropDownList ID="ddlFruits" runat="server">
<asp:ListItem Text="Please Select" Value=""></asp:ListItem>
<asp:ListItem Text="Mango" Value="1"></asp:ListItem>
<asp:ListItem Text="Apple" Value="2"></asp:ListItem>
<asp:ListItem Text="Orange" Value="3"></asp:ListItem>
</asp:DropDownList>
<asp:Button Text="Get Selected Text Value" runat="server" OnClientClick="return GetSelectedTextValue()" />
<script type="text/javascript">
function GetSelectedTextValue() {
var ddlFruits = document.getElementById("<%=ddlFruits.ClientID %>");
var selectedText = ddlFruits.options[ddlFruits.selectedIndex].innerHTML;
var selectedValue = ddlFruits.value;
alert("Selected Text: " + selectedText + " Value: " + selectedValue);
return false;
}
</script>
You can get the value from the list or the selected text (innerHTML) !

SQL SELECT statement with WHERE statement in with DropDownList ASP.NET

Please take a look at the this code:
Dim query As String = "SELECT * From Table Where ID = #UserID"
Dim cmd As SqlCommand = New SqlCommand(query)
cmd.Parameters.AddWithValue("#UserID", DropDownList1.SelectedValue)
and this HTML markup
<asp:DropDownList ID="DropDownList1" runat="server" Width="300px">
<asp:ListItem Text=">>>>>>>>>>> ALL USERS <<<<<<<<<<<" Value="-1" />
<asp:ListItem Text="Tom" Value="1" />
<asp:ListItem Text="Jack" Value="2" />
</asp:DropDownList>
I know y'all understand that when the user select user "tom" will get all data UserID = 1 and if the user select user "Jack" will get all data UserID = 2 right! OK what I need is how to get all the data from table if the user Select "ALL USERS" ?? What can I do in this case? Any ideas?
Dim query As String
IF User = -1 Then
query = "SELECT * From Table "
ELSEIF
query = "SELECT * From Table Where ID = #UserID"
End If
Dim cmd As SqlCommand = New SqlCommand(query)
cmd.Parameters.AddWithValue("#UserID", DropDownList1.SelectedValue)

dropdown list display base on a radio button

I am an amature programmer. I have just start coding around one month
I am trying to write a code which shows the specific values of a database table in a dropdown list based on the radio button checked changed.
I tried to do it by using a session which saves the id of the table values and sends it to the drop down list, but nothing happens
<asp:RadioButton ID="rdbHome" runat="server" AutoPostBack="True"
GroupName="rdb" oncheckedchanged="rdbHome_CheckedChanged" />
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="p" DataValueField="playerID">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:BasketballConnectionString %>"
SelectCommand="PlayerName" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:SessionParameter Name="team1ID" SessionField="team1" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
protected void rdbHome_CheckedChanged(object sender, EventArgs e)
{
string conStr = WebConfigurationManager.ConnectionStrings["BasketballConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("team1ID", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#mID", int.Parse(Request.QueryString["mID"]));
SqlCommand cmd2 = new SqlCommand("matchTeam2", con);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.AddWithValue("#mID", int.Parse(Request.QueryString["mID"]));
try
{
con.Open();
SqlDataReader reader;
reader = cmd2.ExecuteReader();
//reader2 = cmd2.ExecuteReader();
reader.Read();
Session["team1"] = reader["team1ID"].ToString();
cmd.Parameters.AddWithValue("#team1ID", Session["team1"]);
}
catch(Exception ex)
{
lblMsg.Text = "خطا" + ex.Message;
}
}
ALTER PROCEDURE [dbo].[team1ID](#mID INT)
AS
BEGIN
SELECT teamTbl.teamID AS team1ID from
teamTbl join matchTbl ON matchTbl.team1ID=teamTbl.teamID
WHERE matchID=#mID
END
ALTER PROCEDURE [dbo].[matchTeam2](#mID int)
AS
BEGIN
SELECT t1.teamName as team1Name,t2.teamName as team2name,matchTbl.playeName,matchTbl.playerScore,
matchTbl.team1Score,matchTbl.team2Score,team1ID,team2ID
FROM matchTbl JOIN teamTbl as t1 on matchTbl.team1ID=t1.teamID
JOIN teamTbl as t2 on matchTbl.team2ID=t2.teamID
WHERE matchTbl.matchID=#mID
END
and the code for sqlDataSource
ALTER PROCEDURE [dbo].[PlayerName](#team1ID INT)
AS
BEGIN
SELECT playersTbl.playerName, playersTbl.playerID
FROM teamTbl JOIN playersTbl ON teamTbl.teamID=playersTbl.teamID
WHERE teamTbl.teamID=#team1ID
END
It seems that you are not populating the dropdown at all in this case. Inside 'rdbHome_CheckedChanged' method, you should be populating the 'DropDownList1' dropdown control.
Something like the following:
DropDownList1.Items.Add(new ListItem("5", "5%"));
thanks for your help guys, the code worked fine, there were only some silly mistakes in it, the above code is edited and has no problems

DropDownList with DataValueField and DataTextField asp.net C#

In my database, I entry CPVComID value from DropDownList (like
0,1,2,3) and display dataValueFiled value into DropDownList like
(-Select-, Conquest, CBC, Insight Management).
Error Message:
Exception Details: System.ArgumentOutOfRangeException: 'ddlCardCPVComName' has a SelectedValue which is invalid because itdoes not exist in the list of items. Parameter name: value
ASPX:
<asp:DropDownList ID="ddlCardCPVComName" runat="server" AppendDataBoundItems="True"
DataSourceID="SqlDSCPVCompanyName" DataTextField="CPVComName"
dataValueFiled="ddlCardCPVComName" Width="205px" DataValueField="CPVComID">
<asp:ListItem Value="0"> -SELECT- </asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDSCPVCompanyName" runat="server"
ConnectionString="<%$ ConnectionStrings:OptimaWebCustomerQueryCon %>"
SelectCommand="SELECT CPVComID, CPVComName FROM DDCPVCompanyName ORDER BY CPVComID">
</asp:SqlDataSource>
Code Behind:
private void getReceeivedCPV()
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["OptimaWebCustomerQueryCon"].ConnectionString))
{
conn.Open();
string str = #"SELECT CardCPVID, CardID,
CardCPVComName,
CardCPVSentDate, CardCPVStatus, CardCPVRcevDate, CPVRemarks FROM CC_CardCPV Where CardID LIKE '" + GVCPVReceived.SelectedValue + "'";
using (SqlCommand com = new SqlCommand(str, conn))
{
using (SqlDataReader dr = com.ExecuteReader())
{
if (dr.Read())
{
TextBox1.Text = Convert.ToString(dr[2]);
ddlCardCPVComName.SelectedValue = Convert.ToString(dr[2]);
txtCardCPVSentDate.Text = Convert.ToDateTime(dr[3]).ToString("dd MMM yyyy");
ddlCardCPVStatus.SelectedItem.Value = Convert.ToString(dr[4]);
if (dr[5] != DBNull.Value)
{
txtCardCPVRcevDate.Text = Convert.ToDateTime(dr[5]).ToString("dd MMM yyyy");
}
else
{
txtCardCPVRcevDate.Text = "";
}
txtCPVRemarks.Text = Convert.ToString(dr[6]);
}
}
}
conn.Close();
}
}
What should I do? Please suggest me.
I can describe why this exception arises..In the below line of code you are setting a value to the dropdownlist ddlCardCPVComName..
ddlCardCPVComName.SelectedValue = Convert.ToString(dr[2]);
Here the exception says that there is no such an item in the dropdownlist ddlCardCPVComName.So you must check when you bind the dropdownlist ddlCardCPVComName
that there exist the particular item which you are going to set..
Check this binding query and make sure that the desired items are bound to the datasource..
<asp:SqlDataSource ID="SqlDSCPVCompanyName" runat="server"
ConnectionString="<%$ ConnectionStrings:OptimaWebCustomerQueryCon %>"
SelectCommand="SELECT CPVComID, CPVComName FROM DDCPVCompanyName ORDER BY CPVComID">
</asp:SqlDataSource>
If am not wrong, Remove dataValueFiled="ddlCardCPVComName"(DropDown) from Your aspx code and execute.
I just change "dlCardCPVStatus.SelectedItem.Text = Convert.ToString(dr[4]);" and success to do this

How to select all records in a DropDownList

I have this DropDownList:
<asp:DropDownList ID="DropDownList1"
runat="server"
AutoPostBack="true"
DataSourceID="SqlDataSource1"
DataTextField="Categorie"
DataValueField="Cat_ID"
>
</asp:DropDownList>
and the SqlDataSource select * all from [tbl_Cat]
It's used to filter the database via category. It works perfectly, but it only shows the three categories that are in the tbl_Cat. I also want a select all item in the DropDownList.
The DropDownList and the datagrid are not made with code-behind; is it possible to enter a "select all records" option through code-behind?
You need to write the below code which help you to select all option for category.
<asp:DropDownList ID="DropDownList1" AutoPostBack="true" runat="server">
</asp:DropDownList>
In Code behind file
SqlConnection con = new SqlConnection(str);
string com = "select * all from tbl_Cat";
SqlDataAdapter adpt = new SqlDataAdapter(com, con);
DataTable dt = new DataTable();
adpt.Fill(dt);
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
DropDownList1.DataTextField = "Categorie";
DropDownList1.DataValueField = "Cat_ID";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select ALL", "0"));
Now you can check if drop down selected value is 0, if it is 0 then you can load all the records in the grid.
Let me know if any thing i miss.
following is the way to bind DropDownList from codebehind. visit this link for details
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
CODE BEHIND
SqlConnection con = new SqlConnection(str);
string com = "select * all from tbl_Cat";
SqlDataAdapter adpt = new SqlDataAdapter(com, con);
DataTable dt = new DataTable();
adpt.Fill(dt);
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
DropDownList1.DataTextField = "Categorie";
DropDownList1.DataValueField = "Cat_ID";
DropDownList1.DataBind();
May be you have this query,
DropDownList1.Items.Add(new ListItem("Select All", "0"));

Resources