How to retrieve text from dropdownlist? - c#

I must audit the changes into a database. On most pages this works perfect, as there were just textboxes - however on a page I am working on right now, with dropdownlists, my code isn't working.
<td>
<asp:DropDownList ID="DropDownList4" runat="server" DataSourceID="SqlDatacountry" DataTextField="country_name" DataValueField="country_id">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDatacountry" runat="server" ConnectionString="<%$ ConnectionStrings:songtypecons %>" SelectCommand="SELECT * FROM [country_detail]"></asp:SqlDataSource>
</td>
code behind:
string sql1 = "selectcust_fname,cust_mname,cust_lname,cust_birthdate,cust_gender,cust_address,cust_contact_num,cust_country,cust_state,cust_city,cust_zip from cust_detail where cust_id ='" + ds.Tables["filldata"].Rows[0].ItemArray[0].ToString() + "' ";
SqlDataAdapter adpt1 = new SqlDataAdapter(sql1, con);
DataSet ds1 = new DataSet();
adpt1.Fill(ds1, "custdata");
if (ds1.Tables["custdata"].Rows.Count > 0)
{
for (int d = 0; d < DropDownList4.Items.Count; d++)
{
if (ds1.Tables["custdata"].Rows[0].ItemArray[7].ToString() == DropDownList4.Items[d].Text)
{
DropDownList4.Items[d].Selected = true;
break;
}
}
}

If I understand your question clearly, you just need to use your code in your ListControl.SelectedIndexChanged event.
Occurs when the selection from the list control changes between posts
to the server.
<asp:DropDownList ID="DropDownList4" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList4_SelectedIndexChanged" ...>
</asp:DropDownList>
protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e)
{
...
}
As I wrote in my comment, you should always use parameterized queries in your sql commands, your code is open for an SQL Injection attacks.

Related

Searching between 2 column numbers

I want to validate in my webform i have 1 textbox and i want to search number and if the number i search is between the range of 2 numbers in my 2 column i want to show the data in the row of my table.
select * from SSPRequest where StartingSeries = '" + TxtSearch.Text + "' BETWEEN EndingSeries= '"+TxtSearch2.Text+"'"
Well, drop a grid view, and then say have this code:
protected void cmdSearch_Click(object sender, EventArgs e)
{
string strSQL = "select * from SSPRequest where StartingSeries >= #Start " +
" AND EndingSeries <= #End";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST3))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Parameters.Add("#Start", SqlDbType.Int).Value = txtSearch.Text;
cmdSQL.Parameters.Add("#End", SqlDbType.Int).Value = txtSearch2.Text;
conn.Open();
GridView1.DataSource = cmdSQL.ExecuteReader();
GridView1.DataBind();
}
}
}
So whatever the sql matches, the grid will display. Your markup could be say this:
Enter Start Number:
<asp:TextBox ID="txtSearch" runat="server" Style="width:25px;padding-right:25px"></asp:TextBox>
Enter End Number:
<asp:TextBox ID="txtSearch2" runat="server" Style="width:25px;padding-right:25px"></asp:TextBox>
<asp:Button ID="cmdSearch" runat="server" Text="Search" style="padding-left:25px;" CssClass="btn" OnClick="cmdSearch_Click" />
<br />
<br />
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
Looking at your sql posted, it seems a bit wonkey, and does not make sense. I would fire up sql studio, and hand code the sql with two range values and get the sql working, THEN AND ONLY THEN would I attempt the above code.
So FIRST get a working sql statement BEFORE YOU WRITE ONE line of code.

DataList not appearing

I'm having trouble displaying a DataList in a aspx page.
protected void btnAdminExecuteQuery_Click(object sender, EventArgs e)
{
SqlDataAdapter _SqlDA;
try
{
_SqlConnection.Open();
_SqlCommand = new SqlCommand(txtBoxAdminQuery.Text, _SqlConnection);
_SqlDA = new SqlDataAdapter(_SqlCommand);
DataSet _SqlDS = new DataSet();
_SqlDA.Fill(_SqlDS);
_SqlConnection.Close();
DL.DataSource = _SqlDS.Tables[0];
DL.DataBind();
}
catch (Exception ex)
{
if (this._SqlConnection.State == ConnectionState.Open)
{
this._SqlConnection.Close();
}
txtBoxAdminErrorMsg.Text = ex.Message;
}
}
I'm sure the ConnectionString and command are correct because I've tested them, and I can see in the debugger that the DataList has rows, it has Data but it's just not displaying.
This is what I see when I execute the query on the 'Admin Panel'
HTML:
<asp:TextBox ID="txtBoxAdminQuery" runat="server" TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="btnAdminExecuteQuery" runat="server" OnClick="btnAdminExecuteQuery_Click" Text="Execute Query" />
<asp:TextBox ID="txtBoxAdminErrorMsg" runat="server" Enabled="False" Height="68px" ReadOnly="True" TextMode="MultiLine" Width="463px"></asp:TextBox>
<asp:SqlDataSource ID="_SqlDS" runat="server" ConnectionString="<%$ ConnectionStrings:CompanyConnectionString %>" SelectCommand="SELECT * FROM [Accounts]"></asp:SqlDataSource>
<asp:DataList ID="DL" runat="server" CellPadding="1" CellSpacing="1" RepeatColumns="2">
</asp:DataList>
</div>
</form>
My goal is to run custom queries and display the results in the DataList, I know how to configure the DataList through Visual Studio Designer, but if I do it from there the Query is static I can't change it, as far as I know.
Proving that the _SqlDS has data:

My ASP.NET DropDownList is not working

I would like to make a DropDownList inside a panel. This is my code from the codebehind file. But if I execute it, it always says: "in DropdownList it is not allowed to make multiple selections." Do I have to do something with the autopostback? So the error comes when I want to select something else than than "All".
DropDownList1.DataTextField = "Kanal";
DropDownList1.DataValueField = "Kanal";
DropDownList1.AppendDataBoundItems = true;
ListItem limDefault = new ListItem();
limDefault.Selected = true;
limDefault.Text = "All";
limDefault.Value = "-1";
DropDownList1.Items.Add(limDefault);
Then this is my ASP.NET code:
<asp:Panel ID="Panel1" runat="server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CR_SQL %>" SelectCommand="Select * from table" >
</asp:SqlDataSource>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" AutoPostBack="True">
</asp:DropDownList>
</asp:Panel>
I guess you execute the first snippet on every postback which adds the default item every time. Do that only at the first time the page loads, therefore use Page.IsPostBack to check that:
if(!IsPostBack)
{
ListItem limDefault = new ListItem();
limDefault.Selected = true;
limDefault.Text = "All";
limDefault.Value = "-1";
DropDownList1.Items.Add(limDefault);
}

Listview Update not workng

I'm trying to change the Select Command my DataSource uses using a dropdownlist. When the page loads it sets the select command depending on the selected index. When I change the dropdownlist the page refreshes but the data doesn't! Where am I going wrong?
.aspx file
<asp:DropDownList ID="filmFilter" runat="server" OnSelectedIndexChanged="filmFilter_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem Value="">Filter</asp:ListItem>
<asp:ListItem Value="priceASC">Price: Low-High</asp:ListItem>
<asp:ListItem Value="priceDSC">Price: High-Low</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionStringFilms %>"></asp:SqlDataSource>
<asp:ListView ID="ListView1" runat="server" DataKeyNames="filmID" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="ListView1_SelectedIndexChanged">
<ItemTemplate>
...
</ItemTemplate>
<LayoutTemplate>
...
</LayoutTemplate>
</asp:ListView>
code-behind - page load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (filmFilter.SelectedIndex == 0)
{
SqlDataSource1.SelectCommand = "SELECT * FROM [films]";
}
if (filmFilter.SelectedIndex == 1)
{
SqlDataSource1.SelectCommand = "SELECT * FROM [films] ORDER BY [filmPrice]";
}
if (filmFilter.SelectedIndex == 2)
{
SqlDataSource1.SelectCommand = "SELECT * FROM [films] ORDER BY [filmPrice] DESC";
}
}
}
Thanks!
You've got it so your datasource is set on the page_load which is fine but you've wrapped it in
if (!IsPostBack)
{
Which means your code to change the datasource will only happen when you are not in postback (when you change the value of the dropdown you will be in a postback)
Have a read through
http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx
It will help with your understanding

Drop-down Selected Value not Showing in my Detailview

I have drop-down that is not showing the previoiusly selected value in my Detailview. It always shows me the first value in the list. If the previously selected value was xyz then when the Detailvies loads, i want to show xyz. I have researched a lot but could not find any solution that i can use. please help
here is my aspx code for the field that has the dropdown
<asp:TemplateField HeaderText="Name:">
<ItemTemplate>
<asp:Label ID="lbl_UID" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name") %>'></asp:Label></ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl_Name" Width="200px" Height="25" DataSourceID="SDS_Manager" DataTextField="FULL_NM" AutoPostBack="false"
DataValueField="UID" runat="server" AppendDataBoundItems="false">
<asp:ListItem Text="Select Name" Value="Select Name"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
here is the code behind that binds the detailview
protected void Edit(object sender, EventArgs e)
{
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
sqlcon.Open();
sqlcmd = new SqlCommand(#"Select PRJ_ID, WPC_CD, WPC_DESC, Name FROM myTable where PRJ_ID = '" + myvar + "' ", sqlcon);
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
sqlcon.Close();
DV_Edit.DataSource = dt;
DV_Edit.DataBind();
sqlcon.Close();
popup.Show();
}
}
Try setting AutoPostBack="true" and make sure if you have any logic to set the value of the drop down in the page load, that the code is not executed on post back as shown below.
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
ddlOne.DataSource = //your data here;
ddlOne.DataBind();
}
}
//if you don't wrap this logic in the if(!IsPostBack), the code will simply re-populate
//the drop down and set the selected index to the first item in the list with each
//post back.

Categories