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;
Related
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 am using asp DropDownList inside RadGrid, and trying to Add and Update the DropDownList item inside Database table.
Below is the HTML code for DropDownList inside RadGrid's EditItemTemplate:
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>'></asp:Label>
<asp:DropDownList ID="ddlAcCode" DataTextField="AccountDescription" DataValueField="AccountCodeID" runat="server"/>
</EditItemTemplate>
</telerik:GridTemplateColumn>
C# Code:
public DataTable GetAccCode(string CompanyCode)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("[Invoice].[usp_tbl_AccountCode_DL_Test]", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CompanyCode", CompanyCode);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
con.Open();
da.Fill(dt);
con.Close();
}
catch (Exception ex)
{
}
return dt;
}
protected void RGGSTAcCode_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
//bind dropdwon while "Add"
string CompanyCode = ddlCompany.SelectedValue.ToString();
GridEditableItem item = (GridEditableItem)e.Item;
DropDownList ddl = (DropDownList)item.FindControl("ddlAcCode");
ddl.DataSource = GetAccCode(CompanyCode);
ddl.DataTextField = "AccountDescription";
ddl.DataValueField = "AccountCodeID";
ddl.DataBind();
ddl.Items.Insert(0, "- Select -");
//Select particular dropdown value while "Edit"
string accCodeID = item.GetDataKeyValue("AccountCodeID").ToString();
Label lblAcCode2 = item.FindControl("lblAcCode") as Label;
//if (!string.IsNullOrEmpty(lblAcCode2.Text))
//{
ddl.SelectedValue = lblAcCode2.Text;
//}
//string SelectedVal = ddl.SelectedValue;
if (!string.IsNullOrEmpty(lblAcCode2.Text))
{
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("SELECT [AccountCode]+' - '+[AccountDescription] as [AccountDescription] FROM [Sunway_AP].[Invoice].[tbl_AccountCodeTest] where AccountCodeID='" + accCodeID + "' ", con);
DataTable dt = new DataTable();
try
{
adapter.Fill(dt);
}
finally
{
con.Close();
}
ddl.SelectedValue = dt.ToString();
string SelectedVal = ddl.SelectedValue;
}
}
}
This is the Stored Procedure:
ALTER PROCEDURE [Invoice].[usp_tbl_AccountCode_DL_Test]
#CompanyCode nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
SELECT [AccountCodeID] ,[AccountCode]+' - '+[AccountDescription] as [AccountDescription]
FROM [Sunway_AP].[General].[tbl_AccountCode] (NOLOCK)
Where [CompanyCode] = #CompanyCode
order by [AccountCode]+' - '+[AccountDescription]
END
My problem is: I am unable to fetch the "DropDownList's" selected value for a particular Id (particular row of RadGrid), while Edit.
Everytime when I try to set the Selected Value of DropdownList from code behind, it shows me 1st item '- Select -' inside the selected value.
Please reply what is wrong in my code.
I am very new in Telerik. Thanks in advance.
Modified my posted code as below:
protected void RGGSTAcCode_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
//bind dropdwon while "Add"
string CompanyCode = ddlCompany.SelectedValue.ToString();
GridEditableItem item = (GridEditableItem)e.Item;
DropDownList ddl = (DropDownList)item.FindControl("ddlAcCode");
ddl.DataSource = GetAccCode(CompanyCode);
ddl.DataTextField="*your text field*";
ddl.DataValueField="*your Value field*";
ddl.DataBind();
ddl.Items.Insert(0, "- Select -");
Label lblAcCode2 = item.FindControl("lblAcCode2") as Label;
if (!string.IsNullOrEmpty(lblAcCode2.Text))
{
ddl.SelectedItem.Text = lblAcCode2.Text;
ddl.SelectedValue = lblAcCode2.Text;
}
}
}
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddlAcCode" DataTextField="AccountDescription" DataValueField="AccountCodeID" runat="server"/>
</EditItemTemplate>
</telerik:GridTemplateColumn>
Hope this helps...
All the best...
In my webpage, there is a RadComboBox outside the RadGrid and a Dropdown inside RadGrid.
Data inside Dropdown is bind based on RadComboBox item selection.
Ex: If from RadComboBox, item "Company" is selected, then data inside Dropdown will be related to "Company" (i.e, Company1, Company2,company3, etc)
HTML code:
<telerik:RadComboBox ID="ddlCompany" runat="server" Height="200" Width="240"
DropDownWidth="310" EmptyMessage="- Select Product -" HighlightTemplatedItems="true" CausesValidation="false" Filter="StartsWith" AppendDataBoundItems="true" AllowCustomText="true" AutoPostBack="true" DataTextField="Title" DataValueField="Code" OnSelectedIndexChanged="ddlCompany_SelectedIndexChanged">
</telerik:RadComboBox>
<telerik:RadGrid ID="RGGSTAcCode" runat="server">
<Columns>
<telerik:GridEditCommandColumn></telerik:GridEditCommandColumn>
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlAcCode" DataTextField="AccountDescription" DataValueField="AccountCodeID" runat="server"/>
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
C# Code:
public DataSet GetCompanyNames()
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("General.usp_tbl_BuyerCode_Query", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
con.Open();
da.Fill(ds);
con.Close();
}
catch (Exception ex)
{
}
return ds;
}
protected void BindComapnyDL()
{
ddlCompany.DataTextField = "Title";
ddlCompany.DataValueField = "Code";
ddlCompany.DataSource = GetCompanyNames();
ddlCompany.DataBind();
Session["Comp"] = ddlCompany.SelectedValue.ToString();
}
protected void ddlCompany_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
if (ddlCompany.SelectedItem != null)
{
SqlConnection con = new SqlConnection(strcon);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("SELECT [AccountCodeID],[AccountCode]+' - '+[AccountDescription] as[AccountDescription] FROM [Sunway_AP].[General].[tbl_AccountCode] (NOLOCK) Where [CompanyCode] = '" + Session["Comp"] + "' order by [AccountCode]+' - '+[AccountDescription]", con);
con.Open();
DataTable dt = new DataTable();
try
{
adapter.Fill(dt);
}
finally
{
con.Close();
}
DropDownList list = RGGSTAcCode.FindControl("ddlAcCode") as DropDownList;
list.DataTextField = "AccountDescription";
list.DataValueField = "AccountCodeID";
list.DataSource = dt;
list.DataBind();
}
else
{
Response.Write("Please select Company first");
}
}
Now, when I try to change the company using "ddlCompany_SelectedIndexChanged" event,
I get below error:
System.NullReferenceException: Object reference not set to an instance of an object.
at line :
list.DataTextField = "AccountDescription";
Please suggest what is wrong in my code. Thanks in advance
This line contains error dropdown is not properly find
DropDownList list = RGGSTAcCode.FindControl("ddlAcCode") as DropDownList;
Where did You placed Dropdown inside any control..??
visite this link http://docs.telerik.com/devtools/aspnet-ajax/controls/grid/how-to/operations-with-ms-dropdownlist-in-edititemtemplate-of-gridtemplatecolumn
try this
foreach (GridDataItem item in RGGSTAcCode.EditItems)
{
DropDownList list = item.FindControl("ddlAcCode") as DropDownList;
//Now we can do stuff with the "list"
}
Keep in mind that the row needs to be in Edit Mode to find controls in its EditItemTemplate.
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;
}
}
}
I have two dropdown lists and the second is populated based on the selected value of the first. This is how i had my second dropdown list populated but it wasn't filling based on the selected item in the first which lead me to change how i am filling it.
Before:
<asp:DropDownList ID="RootDropDown" runat="server" AutoPostBack="True" DataSourceID="FirstChild" DataTextField="DisplayName" DataValueField="ID"></asp:DropDownList>
<asp:SqlDataSource ID="FirstChild" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnection %>" SelectCommand="SELECT e.DisplayName, e.ID , e.GUID
FROM SomeTable e
INNER JOIN TabletoTableMap em
ON e.ID = em.OtherTableID
WHERE em.SomeTableID = 9"+ ></asp:SqlDataSource>
After:
<asp:DropDownList ID="RootDropDown" runat="server" AutoPostBack="True" DataSourceID="FirstChild" DataTextField="DisplayName" DataValueField="ID" OnSelectedIndexChanged="Child"></asp:DropDownList>
Child Method:
protected void Child(object sender, EventArgs e)
{
String strConnection = "Data Source=.;Initial Catalog=ALE;Integrated Security=True";
int RootID = Convert.ToInt32(CourseDropDown.SelectedValue);
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strConnection);
con.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT e.DisplayName, e.ID , e.GUID FROM SomeTable e INNER JOIN TabletoTableMap em ON e.ID = em.OtherTableID WHERE em.SomeTableID="+RootID, con);
System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(cmd);
System.Data.DataSet ds = new System.Data.DataSet();
da.Fill(ds);
con.Close();
RootElementDropDown.DataSourceID = "FirstChild";
RootElementDropDown.DataTextField = "DisplayName";
RootElementDropDown.DataValueField = "ID";
RootElementDropDown.DataBind();
}
Error:
The DataSourceID of 'RootDropDown' must be the ID of a control of type IDataSource. A control with ID 'FirstChild' could not be found.
Try to Set
DataMember as what you want