asp.net dropdownlist selected value - c#

When I select a value from the dropdownlist, I like that value to be save in the #TimeZone value that is needed for
InsertCommand="INSERT INTO [Companies] ([TimeZone]) VALUES ( #TimeZone)"
I am not sure how to do this.
Here is my code:
Within my page load, I have the following code that assigns value to the drop down:
ddlTimeZone.DataSource = from p in TimeZoneInfo.GetZones()
select new { p.Id };
ddlTimeZone.DataTextField = "Id";
ddlTimeZone.DataValueField = "Id";
ddlTimeZone.DataBind();
Next, within my .aspx file, I have the following:
<EditItemTemplate>
<asp:DropDownList ID="ddlTimeZone" runat="server">
</asp:DropDownList>
</EditItemTemplate>
..... .....
InsertCommand="INSERT INTO [Companies] ([TimeZone]) VALUES ( #TimeZone)"
<InsertParameters>
<asp:Parameter Name="TimeZone" Type="String" />
</InsertParameters>
Again, what I need to know is how to I bind the selected value from the dropdownlist (ddlTimeZone) to #TimeZone
I tried:
<asp:DropDownList ID="ddlTimeZone" SelectedValue='<%# Bind("TimeZone") %>' runat="server">
</asp:DropDownList>
But that did not work. NOTE THAT I AM USING THE DROPDOWNLIST WITHIN A GRIDVIEW.

Try this way
var command = new SqlCommand("INSERT INTO [Companies] ([TimeZone]) VALUES ( #TimeZone)", connection);
command.Parameters.Add(new SqlParameter("#TimeZone", valuetopass));

Related

Add an empty value in dropdown list when using DataSource C#

I'm trying to create a filter through DropDownList.
They are using Datasources.
The problem is - these sources don't include empty value and filter always works. Of course I don't need it. I tryied to add ListItem right incide of DropDownList but it didn't help.
Here is one of my DropDownList.
<asp:DropDownList ID="ddl" runat="server" DataSourceID="sds"
DataTextField="name" DataValueField="id">
</asp:DropDownList>
<asp:SqlDataSource ID="sds" runat="server"
ConnectionString="<%$ ConnectionStrings:conStr %>"
OnInit="sds_Init"></asp:SqlDataSource>>
Will be grateful for your help!
You can do it in code behind:
ddl.Items.Add(new ListItem("--Select--", "-1"));
Or:
ddl.Items.Insert(0, new ListItem("--Select--", "-1"));
Or on your .aspx:
<asp:DropDownList ID="ddl" runat="server" DataSourceID="sds"
DataTextField="name" DataValueField="id">
<asp:ListItem Text="--Select--" Value ="-1"></asp:ListItem>
</asp:DropDownList>
Or potentially in your SQL:
SELECT "--Select--" AS [name], -1 as [id]
UNION
SELECT ...
I am doing the same thing this way, Try this once
AffiliatesDomain affiliateDomain = new AffiliatesDomain();
List<usp_selectAffiliatesForMasterResult> objListAffiliate = new List<usp_selectAffiliatesForMasterResult>();
objListAffiliate = affiliateDomain.SelctAffiliatesForMasterAgent();
ddlAffiliate.DataSource = objListAffiliate;
ddlAffiliate.DataTextField = "PartnerAffiliatCodeName";
ddlAffiliate.DataValueField = "AffiliateId";
ddlAffiliate.DataBind();
ddlAffiliate.Items.Insert(0, new ListItem("--Select--", "0"));

DropDownList resets to the first item

I have two bound to objectdatasource dropdownlists.
<asp:DropDownList ID="ddlProgram" runat="server" DataSourceID="ProgramsDS"
DataTextField="NAME" DataValueField="ID" AutoPostBack="True"
OnSelectedIndexChanged="ddlProgram_SelectedIndexChanged">
</asp:DropDownList>
<asp:ObjectDataSource ID="ProgramsDS" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetData"
TypeName="WebAdminTools.DATA.DSTableAdapters.ProgramTA"
UpdateMethod="Update">
</asp:ObjectDataSource>
<br/>
<asp:DropDownList runat="server" ID="ddlVersion" AutoPostBack="True"
OnSelectedIndexChanged="ddlVersion_SelectedIndexChanged" Width="158px"
DataSourceID="VersionDS" DataTextField="VERSION"
DataValueField="PROGRAM_ID"/>
<asp:ObjectDataSource ID="VersionDS" runat="server"
OldValuesParameterFormatString="original_{0}"
SelectMethod="GetData"
TypeName="WebAdminTools.DATA.DSTableAdapters.UpdateTA">
<SelectParameters>
<asp:ControlParameter ControlID="ddlProgram" DefaultValue="0"
Name="P_ID" PropertyName="SelectedValue" Type="Int32"/>
</SelectParameters>
</asp:ObjectDataSource>
I have onSelectionIndexChanged event handler for the second dropdownlist as well. When I try to pick item from second dropdownlist it resets to first one. I tried this guide What am I doing wrong?
Edit:
protected void ddlVersion_SelectedIndexChanged(object sender, EventArgs e)
{
GetCompaniesForUpdate();
}
private void GetCompaniesForUpdate()
{
ProgramVersionTA ta = new ProgramVersionTA();
var dt = new DS.ProgramsVersionsDataTable();
ta.Fill(dt, Convert.ToInt32(ddlVersion.SelectedValue));
var selectedVersion = Version.Parse(ddlVersion.SelectedValue);
var companyForUpdate = dt.Where(c => Version.Parse(c.MAX_AVAILABLE_VERSION) > selectedVersion
&& Version.Parse(c.VERSION) < selectedVersion);
lbCompanies.DataSource = companyForUpdate;
lbCompanies.DataMember = "NAME";
lbCompanies.DataBind();
}
I think it is because of the postback. if u are setting a value to dropdownlist on form_load, please make sure that u put it inside the if(!Page.IsPostBack).

How to use controls value in mysql query

I have a database with the tables and columns:
persons: id, first_name, last_name
addresses: id, city, street_number, persons_id
I'm trying to make a search engine in asp.net.
I have controls: TextBox1, DropDownList1, Button1, GridView1 with SqlDataSource1.
The DropDownList1 code:
<asp:DropDownList ID="DropDownList1" runat="server"
DataValueField="first_name" AutoPostBack="false">
<asp:ListItem Value="first_name">First name</asp:ListItem>
<asp:ListItem Value="last_name">Last name</asp:ListItem>
<asp:ListItem Value="city">City</asp:ListItem>
</asp:DropDownList>
In the SqlDataSource control: in the SelectCommand I'm trying to make something like this:
SelectCommand="SELECT first_name, last_name, city FROM persons, addresses WHERE persons.id = addresses.persons_id AND (? LIKE '%'??'%')">
In the ? and ?? I want to put the values from DropDownList1 and TextBox1. Any suggestions ?
You will need two asp:ControlParameter's in your SqlDataSource1 like this:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="YourConnectionString"
SelectCommand="SELECT first_name, last_name, city FROM persons, addresses WHERE persons.id = addresses.persons_id AND (#FirstLastCity LIKE '%#SearchString%')">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="FirstLastCity" PropertyName="SelectedValue" />
<asp:ControlParameter ControlID="TextBox1" Name="SearchString" PropertyName="Text" />
</SelectParameters>
</asp:SqlDataSource>
This should be the first step. I am pretty sure that '%#SearchString%' in the SelectCommand will not work. But there must be a way to concatinate %, #SearchString and % in the markup code.
Alternatively you can set parameter values in code behind like this:
SqlDataSource1.SelectParameters.Add("#SearchString", "%" + TextBox1.Text + "%");

DropDownList, getting DataValueField returned in C#

I have a drop down list that pulls data from a database to show some of its options:
<asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="SqlDataSource1"
DataTextField="Name" DataValueField="PK_Task" AppendDataBoundItems="true" CssClass="dropDownList">
<asp:ListItem Selected="True">General Support</asp:ListItem>
<asp:ListItem>Vacation</asp:ListItem>
<asp:ListItem>Sick Leave</asp:ListItem>
<asp:ListItem>Something Else</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [PK_Task], [Name] FROM [Task] WHERE ([PointPerson] LIKE '%' + #PointPerson + '%') AND [Status] NOT LIKE 'Done'">
<SelectParameters>
<asp:QueryStringParameter Name="PointPerson" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
As you can see, I only display the [Name] column:
DataTextField="Name"
But I am also getting the primary key SELECT [PK_Task], [Name] FROM:
DataValueField="PK_Task"
How do I get access to this primary key based on user selection. If a user selects a specific 'name' from the drop down menu, what C# can I use to get the corresponding primary key returned to me so I can save it in a variable?
The closest I have gotten is this, but all it does is return the string "PK_Task":
String taskID = DropDownList3.DataValueField;
You can use the SelectedValue property:
// to set
DropDownList3.SelectedValue = "1";
// to read
string value = DropDownList3.SelectedValue;
try this
String taskID = DropDownList3.SelectedItem.Value;
any way you can use
either
dropdown3.selectedvalue
or
dropdown3.selecteditem.value

checkboxlist databinding to an entity framework table

I have placed a checkboxlist in a formview object.
I would like to store and load the results of the checkboxlist in a table of an entity framework.
I filled the cbl with values and labels coming from a table that has 2 columns, using the DataSourceID, DataTextField and DataValueField attributes but I can't seem to find how to bind the cbl to the entity framework object in order to store the checked values when the formview is in "EDIT" mode.
Any help would be appreciate. Thanks!
<asp:FormView ID="formView1" runat="server" DataSourceID="Ods1"
Height="203px" Width="495px"
onpageindexchanging="formView1_PageIndexChanging">
<EditItemTemplate>
<asp:CheckBoxList ID="cblProducts" runat="server" RepeatColumns="3"
Width="782px" DataSourceID="SqlDataSource1" DataTextField="ProductName"
DataValueField="ProductCode">
</asp:CheckBoxList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [ProductCode], [ProductName] FROM [Products]">
</asp:SqlDataSource>
</EditItemTemplate>
</asp:FormView>
<asp:ObjectDataSource ID="Ods1" runat="server"
DataObjectTypeName="WebApplication1.EDM.Emp" DeleteMethod="DeleteEmp"
InsertMethod="CreateNewEmp" OldValuesParameterFormatString="original_{0}"
SelectMethod="GetEmpByEmpId" TypeName="WebApplication1.EDM.EmpLogic"
UpdateMethod="UpdateEmp" OnSelecting="Ods1_Selecting">
<SelectParameters>
<asp:RouteParameter Name="EmpId" RouteKey="EmpId" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:FormView ID="formView1" runat="server"
OnItemUpdating="formView1_ItemUpdating" ...>
protected void formView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
var cblProducts = formView1.FindControl("cblProducts") as CheckBoxList;
foreach (ListItem item in cblProducts.Items)
{
if (item.Selected)
{
// Check if item.Value is not in the db for this employee, if so add it
}
else
{
// Check if item.Value is in the db for this employee, if so delete it
}
}
// save
}
You need to do the following;
foreach (ListItem chk in cblProducts.Items)
{
string productId= chk.Value;
if (IsProductAvailable(productId) // this method will basically goes to database and return true of false
chk.Selected = true;
else
chk.Selected = false;
}
private void IsProductAvailable(string productId)
{
string query = "SELECT [ProductId] FROM [Product] ";
query += "WHERE [ProductId] = #ProductId";
DbCommand comm = new DbCommand();
comm.CommandText = query;
DbParameter param = comm.CreateParameter();
param.ParameterName = "#ProductId";
param.Value = productId;
comm.Parameters.Add(param);
DataTable table = comm.ExecuteCommand();
if (table.Rows.Count > 0)
{
return true;
}
else
return false;
}
please modify query and parameters according to your need.

Categories