After much much research I cannot find the same problem anywhere, under my circumstances. I've enabled viewstate at the page, control, and individual dropdown levels. Page_Load only loads the dropdown if PostBack true according to code.
The problem is that on postback (triggered by the DropDownList or any control), "Empty Parameter" shows in my debugging label, which tells me it's not grabbing the SelectedValue from the dropdown in its selectedIndexChanged method. Also, my dropdowns reset to their initial value before the PageLoad "PopulateFilterDropdowns" method.
Any ideas? I've been searching here, google, anywhere and everywhere I can go. Everybody's problem is usually a lack of "IsPostback" or EnableViewState="true", but no dice on my end. I will mention this is a ascx UserControl, inside of a page with a MasterPage. But I believe the code of each of those is irrelevant to this problem, and quite large to post here.
Help!?
Dropdown:
<asp:DropDownList ID="ddlTopics" runat="server" EnableViewState="true" AutoPostBack="true" OnSelectedIndexChanged="ddlTopics_SelectedIndexChanged">
<asp:ListItem Text="Topic" Value=""></asp:ListItem>
</asp:DropDownList>
Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateFilterDropdowns();
}
}
Following methods:
public void PopulateFilterDropdowns()
{
PopulateTopicDropdown();
PopulateAssetTypeDropdown();
PopulateLevelDropdown();
}
public void PopulateTopicDropdown()
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["XXX"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("StoredProc", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
//ListItem itm = new ListItem();
//itm.Value = rdr[0].ToString();
//itm.Text = rdr[0].ToString();
ddlTopics.Items.Add(new ListItem(rdr[0].ToString(), rdr[0].ToString()));
}
}
}
}
}
Problem zone:
protected void ddlTopics_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlTopics1 = (DropDownList)sender;
string topic = ddlTopics1.SelectedValue;
if (String.IsNullOrEmpty(topic))
lblDebug.Text = "Empty Parameter";
else
lblDebug.Text = topic;
//PopulateRecordsByTopic(topic);
}
public void PopulateRecordsByTopic(string topic)
{
//Query and Binding of repeater on page
}
Related
I have Use telerik:radcombobox with mutiple select value.I have bind data LoadOndemand.All Work Fine but when i click on submit button then CheckedItems.Count=0.
Thank you,
Dhiren Patel
I believe you are using EnableLoadOnDemand property of the RadComboBox. RadComboBox items are not accessible on the server-side when loading them on demand and therefore always return CheckedItems as well as SelectedItems count as zero and this is a known issue. This is because RadComboBox items loaded on demand using the ItemsRequested event handler or WebService do not exist on the server and cannot be accessed using the server-side FindItemByText / Value methods. SelectedItem and SelectedIndex properties are always Null / Nothing. This is needed for speed (otherwise the combobox will not be that responsive upon each keypress if state information and ViewState were persisted).
Please have a look at the following code without using load on demand which works fine at my end.
<telerik:RadComboBox runat="server" ID="RadComboBox1" CheckBoxes="true">
</telerik:RadComboBox>
<br />
<br />
<telerik:RadButton ID="RadButton1" runat="server" Text="Get Count" OnClick="RadButton1_Click">
</telerik:RadButton>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateRadCombobox("select ContactName from Customers");
}
}
protected void populateRadCombobox(string query)
{
String ConnString =
ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(ConnString);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(query, conn);
DataTable myDataTable = new DataTable();
conn.Open();
try
{
adapter.Fill(myDataTable);
RadComboBox1.DataTextField = "ContactName";
RadComboBox1.DataSource = myDataTable;
RadComboBox1.DataBind();
}
finally
{
conn.Close();
}
}
protected void RadButton1_Click(object sender, EventArgs e)
{
if (RadComboBox1.CheckedItems.Count > 0)
{
//business logic goes here
}
else
{
}
Reference:
http://www.telerik.com/forums/checkeditems-count-always-returns-a-value-of-zero-0
http://www.telerik.com/forums/radcombobox-losing-client-selections-on-postback
I have database with images in folder on my server. To display this images I'am using DataList control. ItemTemplate include also a LinkButton
<asp:LinkButton ID="wybierzZdjecieBtn" OnClick="choosePhotoButton_Click" CommandArgument='<%#Eval("PhotoLinkAddress")%>' CssClass="wybierzZdjecieButton" runat="server">Choose photo</asp:LinkButton>
To receiving Value from LinkButton CommandArgument i'am using this method:
protected void choosePhotoButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)(sender);
string photoLinkAddressVar = button.CommandArgument.ToString();
Response.Write(PhotoLinkAddressVar);
}
This works fine, no problems. But this is not what I want achieve. My intentions is send this variable "PhotoLinkAddressVar" to this method:
protected void addNewNews_Click(object sender, EventArgs e)
{
string trescStatus = "czeka";
string autor = Session["userName"].ToString();
DateTime data = DateTime.Now;
string dataFormat = "";
dataFormat = data.ToString("dd/MM/yyyy H:mm");
string CS = ConfigurationManager.ConnectionStrings["wiadomosciConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
string dodaj = "Insert into News (TytulNews, TrescNews, Autor, Data, Kategoria, Dotyczy, PhotoLinkAddress, Status) values (#TytulNews, #TrescNews, #Autor, #Data, #Kategoria, #Dotyczy, #PhotoLinkAddress, #Status)";
SqlCommand com = new SqlCommand(dodaj, con);
com.Parameters.AddWithValue("#TytulNews", tytulNewsTextBox.Text);
com.Parameters.AddWithValue("#TrescNews", trescTextBox.Text);
com.Parameters.AddWithValue("#Autor", autor);
com.Parameters.AddWithValue("#Data", dataFormat);
com.Parameters.AddWithValue("#Kategoria", kategoria.SelectedValue.ToString());
com.Parameters.AddWithValue("#Dotyczy", dotyczy.SelectedValue.ToString());
com.Parameters.AddWithValue("#PhotoLinkAddress", photoLinkAddressVar);
com.Parameters.AddWithValue("#Status", trescStatus);
com.ExecuteNonQuery();
}
}
User have to choose photo before press "Add News", because if He doesn't do that, he will receive error message. I dont know, how do that. I Was trying declare some kind public variable before PageLoad and do something like this:
protected void choosePhotoButtonButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)(sender);
photoLinkAddressVar = button.CommandArgument.ToString();
}
but that method won't declare the variable. Do You have any idea, how can I achieve that ?.
You could use also the ViewState.
protected void choosePhotoButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)(sender);
string photoLinkAddressVar = button.CommandArgument.ToString();
View["photoLinkAddressVar"]=photoLinkAddressVar;
Response.Write(PhotoLinkAddressVar);
}
Then in the addNewNews_Click method, you coukld retrieve this value with the following way:
com.Parameters.AddWithValue("#PhotoLinkAddress", ViewState["photoLinkAddressVar"]);
For further documantation about ViewState please look here.
I created a dropdown combobox in asp.net. Here it is:
<asp:ComboBox ID="dropdown_course3" runat="server" AutoPostBack="False"
DropDownStyle="DropDownList"
AutoCompleteMode="Suggest" CaseSensitive="False"
ItemInsertLocation="Append">
</asp:ComboBox>
Then i have a button in my page, and when i click it, i want to get the value of selected item in combobox. The button causes postback. Here is my code:
protected void button_conflict_check_button_Click(object sender, EventArgs e)
{
string dr3 = dropdown_course3.Text;
}
But this returns an empty string even though it should not be empty. Also, i tried selectedItem and it returns null. Can anyone help me with this?
And also, here is how i fill the combobox:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable subjects = new DataTable();
CommonFunctions.con.ConnectionString = CommonFunctions.getConnectionString();
CommonFunctions.con.Open();
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [crn], [subj], [numb], [section] FROM Courses", CommonFunctions.con);
adapter.Fill(subjects);
foreach (DataRow dr in subjects.Rows)
{
string displayVal = dr["subj"].ToString() + " " + dr["numb"].ToString() + " " + dr["section"].ToString();
dropdown_course1.Items.Add(new ListItem(displayVal));
dropdown_course2.Items.Add(new ListItem(displayVal));
dropdown_course3.Items.Add(new ListItem(displayVal));
}
}
catch (Exception ex)
{
// Handle the error
}
// Add the initial item - you can add this even if the options from the
// db were not successfully loaded
CommonFunctions.con.Close();
}
}
Thanks
I have found the problem, since i fill the combobox at page load and inside if(!Page.IsPostBack) block, the button causes postback and combobox seems to be empty.
I have a DropDown List where I have brought the values from my Database using code-behind.
I have added a new value after reading data from source, called ".. Add new skill".
Now when user clicks on that item I need a small page (or rather a new page) to open to add the skills that are not mentioned in the DropDownList.
if (!IsPostBack)
{
SqlConnection myConn = new SqlConnection(#"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True");
SqlCommand myCmd = new SqlCommand(
"SELECT SkillName, SkillID FROM Skills", myConn);
myConn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
//Set up the data binding.
DropDownList1.DataSource = myReader;
DropDownList1.DataTextField = "SKillName";
DropDownList1.DataValueField = "SkillID";
DropDownList1.DataBind();
//Close the connection.
myConn.Close();
myReader.Close();
//Add the item at the first position.
DropDownList1.Items.Insert(0, "..Add New Skill");
}
This is my code-behind file.. How do I link that now?
You should use the SelectedIndexChanged event and SelectedValue property:
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(String.Compare(ddl.SelectedValue,"..Add New Skill",true)==0)
Response.Redirect("Add_New_Skill.aspx");
}
Add a SelectedIndexChanged event handler to that dropdown like this
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddl.SelectedIndex == 0)
Response.Redirect("Add_New_Skill.aspx");
}
If you want position of "...Add new skill" to be at last of the list
Use this
ddl.Items.Insert(ddl.Items.Count, "...Add New Skill");
Now to redirect to another page you should do this
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddl.SelectedIndex == ddl.Items.Count-1)
Response.Redirect("Add_New_Skill.aspx");
}
Set AutoPostBack to true. That way when the user changes an option, it will automatically post the page to the server.
Handle this SelectedIndexChanged event, and redirect to your add page there.
Take your user to a add page.
Add the details to the database.
Bring the user back to this page.
List will be reloaded from database, and you till get your value.
No special linking is required.
This is working
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindDropdownlist()
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string getvalue = DropDownList1.SelectedItem.Value;
if (getvalue == "..Add New Skill")
{
Response.Redirect("Default.apsx");
}
}
public void bindDropdownlist()
{
SqlDataAdapter dap = new SqlDataAdapter("select coloumn1,colum2 from table", con);
DataSet ds = new DataSet();
dap.Fill(ds);
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "coloumn1";
DropDownList1.DataValueField = "colum2 ";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "..Add New Skill");
}
}
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</div>
I am trying to create a GridView which will contain a list of users and permission levels that they have access to. Each row will have the following fields: User_ID, Username, Permission1, Permission2, ..., PermissionN, where the values of permissions field are "0" if the user does not have that permission and "1" if they do (note that columns returned by the DAL are not named Permission1, but rather are the actual name of the permission). I would like to represent the data by using CheckBoxes, to allow an admin to quickly grant or revoke permissions to a large number of users at once.
Since I will not know the number of permissions before-hand, I dynamically create TemplateFields and CheckBoxes, and this works fine; the GridView shows the current permission levels of all the users. I run into a problem when I try to update permissions based on the user checking and unchecking boxes.
Once the user is done changing permissions, I have an "Update" button, which of course causes a postback. Since the postback occurs before the OnClick event, by the time I reach OnClick all of the CheckBoxes have been reset to their initial values. Is there a way I can somehow grab the value of the CheckBoxes' Checked property before the postback occurs? Is there another (better) way of doing this? Thanks.
ASPX:
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False"
EnableModelValidation="True" DataKeyNames="ID">
</asp:GridView>
<asp:ObjectDataSource ID="odsUsers" runat="server" SelectMethod="GET_USERS"
TypeName="oDAL">
</asp:ObjectDataSource>
<asp:Button ID="btnUpdate" runat="server" Text="Update Permissions" OnClick="btnUpdate_OnClick"/>
Code Behind:
private static string[] excludeCols = { "ID", "Username" };
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // Removing the IsPostBack check refreshes the GridView when the Update button is clicked
bindGridViewWithHiddenID(gvUsers, ((DataView)odsUsers.Select()).Table, excludeCols);
}
public static bool bindGridViewWithHiddenID(GridView gv, DataTable dt, string[] excludeCols)
{
gv.Columns.Clear();
gv.DataBind();
if (gv != null && dt != null && dt.Rows.Count > 0)
{
DataControlField newField;
foreach (DataColumn column in dt.Columns)
{
if (excludeCols.Contains(column.ColumnName))
{
newField = new BoundField();
((BoundField)newField).DataField = column.ColumnName;
}
else
{
newField = new TemplateField();
((TemplateField)newField).ItemTemplate = new CustomTemplate(column.ColumnName);
}
newField.HeaderText = column.ColumnName;
if (column.ColumnName == "ID" || column.ColumnName.EndsWith("_ID"))
newField.Visible = false;
gv.Columns.Add(newField);
}
gv.DataSource = dt;
gv.DataBind();
return true;
}
return false;
}
// By this time execution reaches here the CheckBoxes have already been reset
protected void btnUpdate_Click(object sender, EventArgs e)
{
...
}
CustomTemplate class:
public class CustomTemplate : ITemplate
{
private string binding;
private static int count = 0;
public CustomTemplate(string colNameBinding)
{
binding = colNameBinding;
}
public void InstantiateIn(Control container)
{
CheckBox chk = new CheckBox();
chk.ID = "chk" + count++;
chk.DataBinding += new EventHandler(this.chk_OnDataBinding);
container.Controls.Add(chk);
}
public void chk_OnDataBinding(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow namingContainer = (GridViewRow)chk.NamingContainer;
DataRowView dataRow = (DataRowView)namingContainer.DataItem;
if (dataRow[binding].ToString() == "1")
chk.Checked = true;
else
chk.Checked = false;
}
This behavior is expected and is normal. It has to do with the Page Life cycle and tracking of ViewState on dynamically added controls. I recommend you read this article from Scott Mitchell, specially the section titled: View State and Dynamically Added Controls.
I tried adding the GridView binding to OnInit() but since the CheckBoxes aren't actually instantiated until the GridView is DataBound, and since DataBinding will revert the GridView back to its original state, I seem to be stuck again.