DropDownList with DataValueField and DataTextField asp.net C# - asp.net

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

Related

DropDownList SelectIndexChanged not working?

This seems to be a common problem. I have tried different solutions but its still not working. This is my code.
HTML:
<div class="form-group">
<label for="exampleInputEmail1">Artist *</label>
<asp:DropDownList ID="artistDropdown" runat="server" CssClass="form-control" AutoPostBack="True" OnSelectedIndexChanged="artistDropdown_SelectedIndexChanged" ViewStateMode="Enabled"></asp:DropDownList>
<asp:TextBox ID="mytest" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="artistDropdown" SetFocusOnError="true" ErrorMessage="Required Field" Font-Bold="True" Font-Names="Arial" Font-Size="X-Small" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:Label ID="lblMessage" runat="server" CssClass="help-block" Visible="False">Cant select Artist with no Manager</asp:Label>
</div>
Function: OnSelectedIndexChanged
protected void artistDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedArtist = artistDropdown.SelectedValue;
mytest.Text = selectedArtist;
string query = "Select [Manager ID] from Artist Where ID = '" + selectedArtist + "'";
string myConnection = dbController.connectionString;
SqlConnection conn = new SqlConnection(myConnection);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
object obj = cmd.ExecuteScalar();
if (obj is System.DBNull)
{
artistDropdown.SelectedValue = "";
lblMessage.Visible = true;
}
else
{
lblMessage.Visible = false;
}
conn.Close();
}
I am loading DropDownList in Page_Load() function and AutoPostBack="True" is set for DropDownList.
I have also made a TextBox which is being set to the selectedValue from DropDownList to check if on OnSelectedIndexChanged is firing. But text box remains empty.
What am I doing wrong?
Did you put the binding of your dropdown in the if (!postback) {} ?
If you rebind the list after every postback, you get the value of the first list item when you reach the artistDropdown_SelectedIndexChanged event.
If this item has an empty string value...

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

Linking SqlDataSource to label for a single item in ASP.NET

I have a asp:SqlDataSource that returns a single row. How do I return that value into a label. I got it working in a asp:DataList but its overkill since its a single record.
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionString %>"
SelectCommand="SELECT STATEMENT">
</asp:SqlDataSource>
<asp:DataList ID="DataList5" runat="server" DataSourceID="SqlDataSource2">
<ItemTemplate>
<asp:Label ID="label1" runat="server" Text='<%# Eval("ID") %>'></asp:Label><br />
</ItemTemplate>
</asp:DataList>
Here is one way to do it in C#:
DataView oDV = (System.Data.DataView)SqlDataSource2.Select(DataSourceSelectArguments.Empty);
Label1.Text = string.Join("|", oDV.Table.Rows[0].ItemArray.Select(p => p.ToString()).ToArray());
I guess my project is using an actual method instead of a property like I first suggested.
You could use a text SqlCommand(String, SqlConnection), passing the select statement and a SqlConnection(String) to your database.
public string GetSelectStatement()
{
SqlConnection conn = new SqlConnection(ConnectionString);
string selectStatement = "SELECT TOP 1 ID FROM Customer";
SqlCommand comm = new SqlCommand(selectStatement, conn);
comm.CommandType = System.Data.CommandType.Text;
SqlDataReader reader = comm.ExecuteReader();
// My code has a while, but you shouldn't need it with only one record
reader.Read();
string ID = (string)reader["ID"];
return ID;
}
Then in your page (aspx) or control (ascx) you can use that method to bind the label text
<asp:Label ID="label1" runat="server" Text='<%# GetSelectStatement() #>'></asp:Label>

How to auto select a item from dropdownlist when page is loaded

I need to auto select an item from dropdownlist when page is loaded.
.aspx code:
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="fullname" DataValueField="fullname">
<asp:ListItem>Any</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:PHSNew %>" SelectCommand="SELECT DISTINCT [fullname] FROM [web_Users] WHERE ([role] = #role) ORDER BY [fullname]">
<SelectParameters>
<asp:Parameter DefaultValue="md" Name="role" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Now for example if dropdownlist has 4 items (John, Albert, Epstien and Any).
in .cs file I run sql query to get a string name, from database which should be selected in this dropdown.
I just used DropDownList1.selectedValue= name. It worked
But now the problem is the data in database keeps on changing. I may get string name = "Renzo". Renzo WAS part of the database but now it's removed. In that case I have to select "Any".
I tried executing this code:
string s = "Albert";
ListItemCollection li = DropDownList1.Items;
foreach (ListItem l in li)
{
string s1 = l.ToString();
if (l.ToString() == s)
{
DropDownList1.SelectedValue = s;
return;
}
else
{
DropDownList1.SelectedValue = "Any";
}
}
And I am calling this code in Page_Load.
But I am able to get only one item from DropDownlist1 and that is "Any".
How can I get all items and auto select a particular item from dropdownlist?
I believe the issue with your code is that you are using l.ToString(). You would want to use l.Value instead in your comparison.
Another way of doing this you can use the find methods of the item collection.
string s = "Albert";
ListItem li = DropDownList1.Items.FindByValue(s);
if (li != null)
{
li.Selected = true;
}
else
{
DropDownList1.SelectedValue = "Any";
}

How do I move this sample aspx code to aspx.cs (to implement code behind)?

I have a dropdownlist which is populated with data from an SQL db. This is what I might have in the aspx file. How do I move (as much as possible) the code from the aspx file to the aspx.cs file to implement the code behind technique?
I mean at least the SELECT portion.
Thanks.
<asp:DropDownList ID="DropDownList1" ... runat="server"/>
...
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Pubs %>"
SelectCommand="SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors] WHERE [state] = #state">
<SelectParameters>
<asp:ControlParameter Name="state" ControlID="DropDownList1" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
suppose you are binding a grid with data source SqlDataSource1 then you can catch SelectedIndexChanged event in codebehind and get data to bind the grid like this:
ASPX file:
<asp:DropDownList ID="DropDownList1" runat="server"
OnSelectedIndexChanged="ddlChanged" />
C# (codebehind):
protected void ddlChanged(object sender, EventArgs e)
{
var cs=..;//get connection string
using(var con=new SqlConnection(cs))
{
using(var com=new SqlCommand(con))
{
com.Open();
com.CommandType = CommandType.Text;
com.CommandText="SELECT [au_id], [au_lname], [au_fname], [state]
FROM [authors] WHERE [state] = #state";
var state=....;//GET VALUE OF STATE FROM DROPDOWN
var p = com.Parameters.Add("#state");//set other properties
p.Value = state;
using(var adptr=new SqlDataAdapter(com))
{
var dtb=new DataTable();
adptr.Fill(dtb);
grid.DataSource=dtb;
grid.DataBind();
}
}
}
}
The SelectCommand is a property of the datasource object you are using. These can be applied in the code behind as needed, but you may want to do it in an overridden Init page function as this might be used quite early on in the asp.net page life cycle. for eg, although I'm not sure exactly where.
protected override OnInit(object sender, EventArgs e)
{
dsMySource.SelectCommand = "SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors] WHERE [state] = #state"
}
You are also going to have to make sure the #state parameter is used correctly in the code behind as well, this can be accessed also as a property (dsMySource.SelectParameters).

Resources