Dropdown List selected value display only one using Asp.net - 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) !

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...

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)

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 formate string of tree view

i have one tree view. i want to formate appended string like grid view:
<ItemTemplate>
<asp:Label ID="lbut_subject" runat="server"
Text='<%#Eval("Inquiry_subject").ToString().Length > 10 ? Eval("Inquiry_subject").ToString().Substring(0,10)+"..." :Eval("Inquiry_subject") %>'
ToolTip='<%# Bind("Inquiry_subject") %>'></asp:Label>
</ItemTemplate>
how ever i want this this to do with my tree view:
<asp:TreeView ID="TV_Question_Summary" runat="server" ImageSet="Simple" ShowLines="True" OnTreeNodeDataBound="TV_Question_Summary_DataBound" SkipLinkText="">
<DataBindings>
<asp:TreeNodeBinding DataMember="Root" FormatString=" {0}" TextField="" ValueField=""/>
<asp:TreeNodeBinding DataMember="ParentNode" FormatString=" {0}" TextField="Inquiry_id" ValueField="Inquiry_id"/><asp:TreeNodeBinding DataMember="Node" FormatString=" {0}" TextField="body" ValueField="Inquiry_id" ToolTip="body"/>
</DataBindings>
</asp:TreeView>
i want to string presentation like ... if Node filed body string gets overflow of no of 15 chars...
for binding up text i use this code:
void fill_Tree()
{
using (SqlConnection conn = Util.GetConnection())
{
conn.Open();
SqlCommand SqlCmd = new SqlCommand("Select * from tbl_Inquiry_History Where (IsDisplay='True')", conn);
SqlDataReader Sdr = SqlCmd.ExecuteReader();
SqlCmd.Dispose();
string[,] ParentNode = new string[100, 2];
int count = 0;
while (Sdr.Read())
{
ParentNode[count, 0] = Sdr.GetValue(Sdr.GetOrdinal("Inquiry_id")).ToString();
ParentNode[count++, 1] = Sdr.GetValue(Sdr.GetOrdinal("Inquiry_id")).ToString();
}
Sdr.Close();
for (int loop = 0; loop < count; loop++)
{
TreeNode root = new TreeNode();
root.Text = ParentNode[loop, 1];
root.NavigateUrl = "~/Admin/OWM_Inquiry.aspx?inquiryid="+ ParentNode[loop, 1];
SqlCommand Module_SqlCmd = new SqlCommand("Select * from tbl_Question where (Inquiry_id = #parent_id AND IsCount='False')", conn);
Module_SqlCmd.Parameters.AddWithValue("#parent_id", ParentNode[loop, 0]);
SqlDataReader Module_Sdr = Module_SqlCmd.ExecuteReader();
while (Module_Sdr.Read())
{
TreeNode child = new TreeNode();
child.Text = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("body")).ToString();
child.NavigateUrl = "~/Admin/OWM_Inquiry.aspx?inquiryid="+ParentNode[loop, 0];
root.ChildNodes.Add(child);
}
Module_Sdr.Close();
TV_Question_Summary.Nodes.Add(root);
}
TV_Question_Summary.CollapseAll();
}
}
please help me...
Try using a code-behind method instead of embedded code blocks, like this:
protected string DisplayInquirySubject(string inquirySubject)
{
return inquirySubject.Length > 10
? inquirySubject.Substring(0, 10)
: inquirySubject;
}
Now in your markup, you can call the method like this:
<ItemTemplate>
<asp:Label ID="lbut_subject" runat="server"
Text='<%# DisplayInquirySubject(Eval("Inquiry_subject").ToString()) %>'
ToolTip='<%# Bind("Inquiry_subject") %>'>
</asp:Label>
</ItemTemplate>
This has two benefits, it simplifies your markup logic and it allows you to leverage the power of the Visual Studio code editor (i.e. Intellisense and debugging).

First Item on Dropdownlist in blank

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")

Resources