I'm attempting to databind a CheckBoxList but only the last item is being selected.
ASPX:
<asp:CheckBoxList ID="CityCheckBoxList" runat="server"
DataSourceID="SqlDS1" DataTextField="City"
DataValueField="CityID" AutoPostBack="True">
</asp:CheckBoxList>
<asp:SqlDataSource ID="SqlDS1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
Code Behind:
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
EmployeeIdTextBox.Text = sdr["EmployeeID"].ToString();
EmployeeNameTextBox.Text = sdr["EmployeeName"].ToString();
CityCheckBoxList.DataBind();
ListItem currentCheckBox = CityCheckBoxList.Items.FindByValue(sdr["CityID"].ToString());
if (currentCheckBox != null)
{
currentCheckBox.Selected = true;
}
}
}
If the employee belongs to more than one city, only the last one is showing checked in the CityCheckBoxList. What am I doing wrong?
I think because you are binding CityCheckBoxList on every employee from the database. Data binding for checkboxes should be moved outside the loop. Try this:
using (SqlDataReader sdr = cmd.ExecuteReader())
{
CityCheckBoxList.DataBind();
while (sdr.Read())
{
EmployeeIdTextBox.Text = sdr["EmployeeID"].ToString();
EmployeeNameTextBox.Text = sdr["EmployeeName"].ToString();
ListItem currentCheckBox = CityCheckBoxList.Items.FindByValue(sdr["CityID"].ToString());
if (currentCheckBox != null)
{
currentCheckBox.Selected = true;
}
}
}
Related
So I want to make my dropdownlist to have always the same index selected, for example I have a gridview and I have a pager on it, if I change the page the index I had in my dropdownlist resets and I can give other example, I have a search textbox in my page and if I search something on it when I press enter the dropdownlist resets once again. How can I make my dropdownlist to have always the same selected index?
asp.net
<asp:GridView ID="MyGrid" runat="server"
DataKeyNames="No_" AutoGenerateColumns="false" Style="color: Black; border-collapse: collapse; margin-right: auto; display: table; text-align: center;" OnPageIndexChanging="MyGrid_PageIndexChanging" OnRowDataBound="MyGrid_RowDataBound" AllowPaging="True" OnPageIndexChanged="MyGrid_PageIndexChanged" PageSize="10" AllowCustomPaging="False">
<Columns>
<asp:BoundField DataField="No_" HeaderText="No_Encomenda" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings Mode="NumericFirstLast" PageButtonCount="4" FirstPageText="First" LastPageText="Last" />
<PagerStyle CssClass="gridview" HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:GridView>
cs
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["constring"].ConnectionString);
List<string> MySelected;
protected void Page_Load(object sender, EventArgs e)
{
ButtonBack.Visible = false;
//GridView1.Visible = false;
con.Open();
SqlCommand cmd = new SqlCommand("Select bl from booking", con);
SqlDataReader sdr = cmd.ExecuteReader();
DropDownList1.Items.Clear();
DropDownList1.Items.Add("-");
if(IsPostBack == false)
{
while (sdr.Read())
{
DropDownList1.Items.Add(sdr.GetValue(0).ToString());
}
}
if (IsPostBack == false)
{
MySelected = new List<string>();
LoadGrid();
ViewState["MySelected"] = MySelected;
}
else
{
MySelected = (List<string>)ViewState["MySelected"];
}
string user = Convert.ToString(Session["user"]);
username.Text = user;
if (Session["user"] == null || Session["login"] == null)
{
Response.Redirect("Login.aspx", false);
}
if (!Page.IsPostBack)
{
refreshdata();
refreshdata();
}
con.Close();
}
public void LoadGrid()
{
SqlCommand cmd = new SqlCommand("select DISTINCT No_ from [EncomendaTEMP]", con);
{
DataTable rst = new DataTable();
rst.Load(cmd.ExecuteReader());
MyGrid.DataSource = rst;
MyGrid.DataBind();
}
}
public void refreshdata()
{
SqlCommand cmd = new SqlCommand("select DISTINCT No_ from [EncomendaTEMP]", con);
{
DataTable rst = new DataTable();
rst.Load(cmd.ExecuteReader());
MyGrid.DataSource = rst;
MyGrid.DataBind();
}
}
In Page_Load code, I see that you are loading data in dropdownlist. When the page is submitted, Page_Load will execute and it will reload the data in the dropdown list. That's why selection goes off.
You should load the data in the dropdown list only during first load of the page. As you are doing with LoadGrid(). During post back the data of the dropdown and selection will be maintained if you don't reload them.
So I suggest following code change for loading data in dropdown list.
if(!IsPostBack)
{
SqlCommand cmd = new SqlCommand("Select bl from booking", con);
SqlDataReader sdr = cmd.ExecuteReader();
DropDownList1.Items.Clear();
DropDownList1.Items.Add("-");
while (sdr.Read())
{
DropDownList1.Items.Add(sdr.GetValue(0).ToString());
}
MySelected = new List<string>();
LoadGrid();
ViewState["MySelected"] = MySelected;
}
else
{
MySelected = (List<string>)ViewState["MySelected"];
}
I hope this will help you solve your problem.
<asp:ComboBox ID="cmbNames"
runat="server"
OnSelectedIndexChanged="cmbNames_SelectedIndexChanged"
DataSourceID="SqlDataSource1"
DataTextField="name"
DataValueField="id"
MaxLength="0"
style="display: inline;"
AutoPostBack="true">
</asp:ComboBox>
Used this datasource for for adding values to the combobox.
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Tender_Module1ConnectionString %>" SelectCommand="SELECT [name] ,[id]FROM [contract]"></asp:SqlDataSource>
This is code of combobox.
protected void cmbNames_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlCommand cmds = new SqlCommand("select name,street,town,dist from contract where name=#names", con))
{
con.Open();
cmds.Parameters.AddWithValue("#names", cmbNames.SelectedIndex.ToString());
using (SqlDataReader dr = cmds.ExecuteReader())
{
if (dr.Read())
{
street.Text = dr[1].ToString();
town.Text = dr[2].ToString();
dist.Text = dr[3].ToString();
}
}
}
}
But the code is not working and autofill fails. Please help...
I just want to show the amount whenever I click the items in the drop down list.
I tried....
if(ddl.SelectedIndex == 1)
{
txtAmount.Text = "240";
}
I used this:
string SQL = #"SELECT Product FROM Supplies";
using (SqlCommand cmd = new SqlCommand(SQL, con))
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
ddlProduct.DataSource = dr;
ddlProduct.DataTextField = "Product";
ddlProduct.DataBind();
ddlProduct.Items.Insert(0, new ListItem("Select one...", ""));
}
You can select value field from the database and bind it to drop down list as below
string SQL = #"SELECT Product, Price FROM Supplies";
using (SqlCommand cmd = new SqlCommand(SQL, con))
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
ddlProduct.DataSource = dr;
ddlProduct.DataTextField = "Product";
ddlProduct.DataValueField = "Price ";
ddlProduct.DataBind();
ddlProduct.Items.Insert(0, new ListItem("Select one...", ""));
}
then, you can get the selected value and set the textbox text as below
protected void itemSelected(object sender, EventArgs e)
{
txtAmount.Text = ddlProduct.SelectedValue.ToString();
}
for that you need to add event on selectedindexchanged
<asp:DropDownList ID="ddlProduct" runat="server"
onselectedindexchanged="itemSelected" AutoPostBack="True" >
</asp:DropDownList>
Just write the below code in selectedIndexChanged event of your dropdownlist
txtAmount.Text = ddlProduct.SelectedValue;
You add the OnSelectedIndexChanged event to the DropDownList and set AutoPostback to true
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text="Select one..." Value=""></asp:ListItem>
<asp:ListItem Text="Silk" Value="1"></asp:ListItem>
<asp:ListItem Text="Wool" Value="2"></asp:ListItem>
<asp:ListItem Text="Cotton" Value="3"></asp:ListItem>
</asp:DropDownList>
And in code behind
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
decimal amount = 0;
if (!string.IsNullOrEmpty(DropDownList1.SelectedValue))
{
//get amount from somewhere
//amount =
}
txtAmount.Text = string.Format("{0:C}", amount);
}
I have a gridview set in ASP.Net that has a name and a checkbox.
<h4>Current Instructor</h4>
<div class="hide-overflow">
<asp:GridView runat="server" ID="GridViewInstructor" DataSourceID="SqlDataSourceInstructor" AutoGenerateColumns="false" CssClass="table table-bordered table-striped" ShowHeader="false" EmptyDataText="No Instructor associated to class." DataKeyNames="Instructor">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CBInstructorPrimary" runat="server" Checked='<%#Eval("Primary")%>' OnCheckedChanged="PrimaryUpdate" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="InstructorName" />
</Columns>
</asp:GridView>
<asp:SqlDataSource runat="server" ID="SqlDataSourceInstructor" DataSourceMode="DataReader" ConnectionString="<%$ ConnectionStrings:HRAgriConnectionString %>"
SelectCommand="
SELECT a.Primary, a.ClassID, a.Instructor, b.LName + ', ' + b.FName as InstructorName
FROM tblClass a
LEFT JOIN tblUser b
ON a.Instructor = b.UserName
WHERE a.ClassID = #classID
ORDER BY a.Primary DESC">
<SelectParameters>
<asp:QueryStringParameter Name="classID" QueryStringField="cid" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</div>
This makes a gridview table that looks like
my c# code behind looks like this
protected void PrimaryUpdate(object sender, EventArgs e)
{
//CheckBox activeCheckBox = sender as CheckBox;
//foreach (GridViewRow rw in GridViewInstructor.Rows)
//{
// CheckBox chkBx = (CheckBox)rw.FindControl("CBInstructorPrimary");
// if (chkBx != activeCheckBox)
// {
// chkBx.Checked = false;
// }
// else
// {
// chkBx.Checked = true;
// }
//}
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "UPDATE tblClass SET [Primary] = #Primary WHERE classID=#classID and Instructor = #InstructorName";
cmd.Connection = con;
con.Open();
foreach (GridViewRow row in GridViewInstructor.Rows)
{
//Get Instructor Name.
string InstructorName = row.Cells[0].Text;
//Get the Class Id from the DataKey property.
classID = Request.QueryString["cid"];
//Get the checked value of the CheckBox.
bool Primary = (row.FindControl("CBInstructorPrimary") as CheckBox).Checked;
//Save to database
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#InstructorName", InstructorName);
cmd.Parameters.AddWithValue("#classID", classID);
cmd.Parameters.AddWithValue("#Primary", Primary);
cmd.ExecuteNonQuery();
}
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
The outcome should be if you check another checkbox it will update the Primary field (which is a bit field) to 1 if checked and all others in that group will be set to 0. And only 1 checkbox can be checked at a time. I know I have commented out the top part for now. I just haven't been able to figure out how to get this working.
I have a DropDownList in a GridView and I am wanting to have the selected value be whatever the value for that particular person is in the database
My ASP Code for the DropDownList:
<asp:TemplateField HeaderText="Team" SortExpression="Team">
<ItemTemplate>
<asp:DropDownList ID="ddlTeam" runat="server"
DataSourceID="SqlDataSource1" DataTextField="Team"
DataValueField="Team" ondatabound="ddlTeam_DataBound">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:connectionString %>"
SelectCommand="SELECT DISTINCT [Team] FROM [Team_Names]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
My ddlTeam_OnBound:
protected void ddlTeam_DataBound(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
foreach (ListItem item in ddl.Items)
{
if (item.Text == "valor")
{
item.Text = "Team Valor";
}
else if (item.Text == "mystic")
{
item.Text = "Team Mystic";
}
}
}
UPDATE - No Error but DDL is empty:
DropDownList ddl = new DropDownList();
string query2 = "SELECT team_name FROM sec WHERE job = " + TextBox1.Text;
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(query2, con))
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while(read.Read())
{
ddl.SelectedValue = read["team_name"].ToString();
}
}
con.Close();
}
}
Do everything in a query in SqlDataSource and don't use code behind without necessity.
<asp:TemplateField HeaderText="Team" SortExpression="Team">
<ItemTemplate>
<asp:DropDownList ID="ddlTeam" runat="server"
DataSourceID="SqlDataSource1" DataTextField="Team_txt"
DataValueField="Team"><%--No need ondatabound="ddlTeam_DataBound"--%>
</asp:DropDownList><%--datasourceId must match --%>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:connectionString %>"
SelectCommand="SELECT DISTINCT [Team],case Team when 'valor' then 'Team Valor' when 'mystic' then 'Team Mystic' else Team end team_txt FROM [Team_Names]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
You aren't executing the SqlCommand or opening a SqlConnection. You should put your input into a parameter to prevent a potential SQL Injection attack.
As an example:
string teamName = string.Empty;
using (SqlConnection connection = new SqlConnection("your connection string"))
{
connection.Open();
string query = "SELECT DISTINCT team_name FROM sec WHERE job = #job";
SqlParameter param = new SqlParameter
{
ParameterName = "#job",
Value = TextBox1.Text
};
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.Add(param);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow);
if (reader.Read())
{
teamName = reader.GetString(0);
// or
int ord = reader.GetOrdinal("team_name");
teamName = reader.GetString(ord); // Handles nulls and empty strings.
}
}
}
EDIT
You also have to set up your drop down list correctly.
DropDownList ddl = new DropDownList();
ddl.DataSource = // call your database code - see above
ddl.DataValueField = "ValueProperty";
ddl.DataTextField = "TextProperty";
ddl.DataBind();
ddl.SelectedValue = teamName;