I am using ASP.NET dynamic data. In Insert.aspx page, I have a couple of dropdowns to be selected. The fields represented by Dropdown are Required fields in database. So dropdown does not show 'Select' as default option in dropdown. I want to add 'Select' option at top of other records from database shown in dropdown. Note that field is not Required field, hence 'Select' option is not being show over there by dynamic data by default. How can I accomplish this?
Add your "select" item after binding your dropdownlists by using Insert method :
myDropDownList.DataBind();
// To make it the first element at the list, use 0 index :
myDropDownList.Items.Insert(0, new ListItem("Select", string.Empty));
I would create a custom FieldTemplate for Required DropDown fields. Insert the "Select" item during the OnDataBinding event of the control. I would also have a client side RequiredFieldValidator to make sure something other than "Select" is chosen before it can post back.
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ForeignKeyRequired_Edit.ascx.cs"
Inherits="DDWANorthwind.DynamicData.FieldTemplates.ForeignKeyRequired_Edit" %>
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="droplist">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="DropDownList1" ErrorMessage="Selection Required"></asp:RequiredFieldValidator>
-
protected override void OnDataBinding(EventArgs e)
{
base.OnDataBinding(e);
if (Mode == DataBoundControlMode.Edit)
{
string foreignkey = ForeignKeyColumn.GetForeignKeyString(Row);
ListItem item = DropDownList1.Items.FindByValue(foreignkey);
if (item != null)
{
DropDownList1.SelectedValue = foreignkey;
}
}
else if (Mode == DataBoundControlMode.Insert &&
Column.IsRequired)
{
DropDownList1.Items.Insert(0, new ListItem("Select", ""));
}
}
-
you would have to use the UIHint attribute so that this FieldTemplate would be used over the default.
Adding a top element at index 0 works just fine, but LINQ offers another possibility, to return the "select" or "pick something" or "all" as part of the data. A drop-down list was databound to this function:
public static List<string> GetRegions()
{
using (NorthwindDataContext nw = new NorthwindDataContext())
{
IQueryable<string> regionQuery = nw.Customers
.Where(c => c.Region != null)
.OrderBy(c => c.Region)
.Select(c => c.Region)
.Distinct();
return (new List<string>() { "All" }).Concat(regionQuery).ToList();
}
}
//---Populate Category DropDownList
private void getData()
{
var category = (from c in CoffeeContext.tblProductTypes
select new { c.ProductType, c.Description }).ToList();
cbxCategory.DataTextField = "Description";
cbxCategory.DataValueField = "ProductType";
cbxCategory.DataSource = category;
cbxCategory.DataBind();
cbxCategory.Items.Insert(0, "--Select Type--");
cbxCategory.SelectedIndex = 0;
}
Select Top 1 '0' as valueField, '--Select--' as textField from dummtable
UNION
select ID,text from yourTable
Control from backend gives much more flexibility
Related
I am having one gridview and check box for each row of gridview and one button outside gridview.
If I click on button then it should check for atmost one checkbox should be checked, otherwise it will display a message and return from loop.
But how to get the checkbox selected length in gridview in serverside.
If you just want to check if there is a checkbox checked in the gridview you can do this in the button:
bool isChecked = theGridview.Rows
.Cast<GridViewRow>()
.Any(a => ((CheckBox)a.FindControl("yourCheckbox")).Checked);
Do not forget using System.Linq;
You need to loop trough the row of the gridview and look for the checkbox as follows
foreach (GridViewRow r in YourGridView.Rows)
{
foreach(string cnt in controls){
int value = Convert.ToInt32(((System.Web.UI.HtmlControls.HtmlInputCheckBox)r.FindControl(cnt)).Value);
bool isChecked = ((System.Web.UI.HtmlControls.HtmlInputCheckBox)r.FindControl(cnt)).Checked;
//now you have id and checked/unchecked. use your query to save it to database
}
}
Manipulate this according to you requirement.
foreach (GridViewRow gvrow in final.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("CheckBox1");
if (chk != null & chk.Checked)
{
//Perform action 1
}
else
{
// perform action-2
}
I would like to bind 'Id', 'Name' and 'Email' from DataTable to RadComboBox. It's possible with ItemTemplate. But I don't want to display 'Email' column in the RadComboBox. I want display 'Email' in the label when the selectedIndexChanged. Is this possible?
Thank you..
Yes, you can bind these three items within the RadComboBox by using the template. Check out this demo: http://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/templates/defaultcs.aspx
Also, to display email when an item is selected, set the DataTextField="Email", which is the value that should appear when the selection is made.
HTH.
adding custom attributes to the RadComboBox is also a good option.
protected void RadComboBox_ItemsRequested(object sender, Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs e)
{
try
{
RadComboBox myRadComboBox = (RadComboBox)sender;
_rowsOfData = Db.getPeopleOfInterest();
foreach (row _row in _rowsOfData)
{
RadComboBoxItem item = new RadComboBoxItem
{
Text = _row.Name,
Value = _row.Id.ToString()
};
string eMail = _row.Email;
item.Attributes.Add("Email", Email);
item.DataBind();
}
}
catch (Exception ex)
{
HandleException(ex, true);
}
}
Then to display that on the GUI just use something like :
<td>
<%# DataBinder.Eval(Container, "Attributes['Name']")%>
</td>
I am currently facing a problem. How to get the latest selected value from a asp.net checkbox list?
From looping through the Items of a checkbox list, I can get the highest selected index and its value, but it is not expected that the user will select the checkbox sequentially from lower to higher index. So, how to handle that?
Is there any event capturing system that will help me to identify the exact list item which generates the event?
If I understood it right, this is the code I'd use:
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
int lastSelectedIndex = 0;
string lastSelectedValue = string.Empty;
foreach (ListItem listitem in CheckBoxList1.Items)
{
if (listitem.Selected)
{
int thisIndex = CheckBoxList1.Items.IndexOf(listitem);
if (lastSelectedIndex < thisIndex)
{
lastSelectedIndex = thisIndex;
lastSelectedValue = listitem.Value;
}
}
}
}
Is there any event capturing system that will help me to identify the exact list item which generates the event?
You use the event CheckBoxList1_SelectedIndexChanged of the CheckBoxList. When a CheckBox of the list is clicked this event is called and then you can check whatever condition you want.
Edit:
The following code allows you to get the last checkbox index that the user selected. With this data you can get the last selected value by the user.
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = string.Empty;
string result = Request.Form["__EVENTTARGET"];
string[] checkedBox = result.Split('$'); ;
int index = int.Parse(checkedBox[checkedBox.Length - 1]);
if (CheckBoxList1.Items[index].Selected)
{
value = CheckBoxList1.Items[index].Value;
}
else
{
}
}
Below is the code which gives you the Latest selected CheckBoxList Item.
string result = Request.Form["__EVENTTARGET"];
string [] checkedBox = result.Split('$'); ;
int index = int.Parse(checkedBox[checkedBox.Length - 1]);
if (cbYears.Items[index].Selected)
{
//your logic
}
else
{
//your logic
}
Hope this helps.
Don't know about you, but as a user i wouldn't want the page to post back every time a checkbox item was checked.
This is the solution i would go with (jQuery):
Declare a server-side hidden field on your form:
<asp:HiddenField ID="HiddenField1" runat="server" EnableViewState="true" />
Then wire up client-side event handlers for the checkboxes to store checkbox clicked:
$('.someclassforyourcheckboxes').click(function() {
$('#HiddenField1').val($(this).attr('id'));
This is a lightweight mechanism for storing the ID of the "latest" checkbox clicked. And you won't have to set autopostback=true for the checkboxes and do an unecessary postback.
You dont HAVE to use jQuery - you can use regular Javascript, but, why do more work? =)
Then when you actually do the postback (on a submit button click i assume), just check the value of the hidden field.
Unless of course you WANT to postback on every checkbox click, but i can't envision a scenario in which you'd want this (maybe you're using UpdatePanel).
EDIT
The HTML of a checkbox list looks like this:
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike
So, you can access three things:
Vehicle = $(this).attr('name');
Bike = $(this).attr('value');
I have a bike = $(this).html();
If you're trying to access the databound value, try the second technique.
Give that a try.
I am using the AJAX Cascading drop down list but want to add event validation e.g. the compare validators.
As the cascading drop down list requires the page event validation to be disabled what is the best way to do the validation?
Thanks
Andy
Validation Attempt:
I have tried to use a custom validator which calls a Javascript function but it doesnt seem to be picking up the control. I get the following error Microsoft JScript runtime error: Object required
function ValidateCostCentCat(source, arguments)
{
var countryList = document.getElementById("ddlCategory");
if (null != countryList)
{
var iValue = countryList.options[countryList.selectedIndex].value;
if (iValue == "Select Category")
{
arguments.IsValid = true;
}
else
{
arguments.IsValid = false;
}
}
}
The mark-up for the custom validator is
<asp:CustomValidator ID="valcustCategory" runat="server" CssClass="error" Display="Dynamic" ValidationGroup="DirectHire" ClientValidationFunction="ValidateCostCentCat"
ErrorMessage="Please select a Cost Centre Category from the drop down list provided.">!</asp:CustomValidator>
Read This: http://www.w3schools.com/PHP/php_ajax_database.asp
The example demostrate how to select a
value from a dropdown box sent it via
AJAX and get back the responce!
in the middle you can do all the
Validation that you want!
UPDATED with code just for fun! ;-)
Assuming your select is
<asp:DropDownList ID="CategoryDropDownList" runat="server">
Then you function look like this:
function ValidateCostCentCat(source, arguments)
{
var countryList = document.getElementById("CategoryDropDownList");
if (null != countryList)
{
var iValue = countryList.options[countryList.selectedIndex].value;
if ( iValue == "Select Category" ) {
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
}
This must work as expected!
hope this help!
I have a page with a table of stuff and I need to allow the user to select rows to process. I've figured out how to add a column of check boxes to the table but I can't seem to figure out how to test if they are checked when the form is submitted. If they were static elements, I'd be able to just check do this.theCheckBox but they are programaticly generated.
Also I'm not very happy with how I'm attaching my data to them (by stuffing it in there ID property).
I'm not sure if it's relevant but I'm looking at a bit of a catch-22 as I need to known which of the checkboxes that were created last time around were checked before I can re-run the code that created them.
Edit:
I've found an almost solution. By setting the AutoPostBack property and the CheckedChanged event:
checkbox.AutoPostBack = false;
checkbox.CheckedChanged += new EventHandler(checkbox_CheckedChanged);
I can get code to be called on a post back for any check box that has changed. However this has two problems:
The call back is processed after (or during, I'm not sure) Page_Load where I need to use this information
The call back is not called for check boxes that were checked when the page loaded and still are.
Edit 2:
What I ended up doing was tagging all my ID's with a know prefix and stuffing this at the top of Form_Load:
foreach (string v in this.Request.Form.AllKeys)
{
if (v.StartsWith(Prefix))
{
var data = v.Substring(Prefix.Length);
}
}
everything else seems to run to late.
I'm going to assume you're using a DataList but this should work with and Control that can be templated. I'm also going to assume you're using DataBinding.
Code Front:
<asp:DataList ID="List" OnItemDataBound="List_ItemDataBound" runat="server">
<ItemTemplate>
<asp:CheckBox ID="DeleteMe" runat="server"/>
<a href="<%# DataBinder.Eval(Container, "DataItem.Url")%>" target="_blank">
<%# DataBinder.Eval(Container, "DataItem.Title")%></a>
</ItemTemplate>
</asp:DataList>
<asp:Button ID="DeleteListItem" runat="server" OnClick="DeleteListItem_Click" ></asp:Button>
Code Behind:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadList();
}
protected void DeleteListItem_Click(object sender, EventArgs e)
{
foreach (DataListItem li in List.Items)
{
CheckBox delMe = (CheckBox)li.FindControl("DeleteMe");
if (delMe != null && delMe.Checked)
//Do Something
}
}
LoadList();
}
protected void LoadList()
{
DataTable dt = //Something...
List.DataSource = dt;
List.DataBind();
}
protected void List_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
string id = DataBinder.Eval(e.Item.DataItem, "ID").ToString();
CheckBox delMe = (CheckBox)e.Item.FindControl("DeleteMe");
if (delMe != null)
delMe.Attributes.Add("value", id);
}
}
}
First, make sure that each Checkbox has an ID and that it's got the 'runat="server"' in the tag.
then use the FindControl() function to find it.
For example, if you're looping through all rows in a GridView..
foreach(GridViewRow r in Gridview1.Rows)
{
object cb = r.FindControl("MyCheckBoxId");
if(r != null)
{
CheckBox chk = (CheckBox)cb;
bool IsChecked = chk.Checked;
}
}
Postback data is restored between the InitComplete event and the PreLoad event. If your checkboxes are not created until later then the checkboxes will play "catch up" with their events and the data will be loaded into the control shortly after it is created.
If this is to late for you then you will have to do something like what you are already doing. That is you will have to access the post data before it is given to the control.
If you can save the UniqueId of each CheckBox that you create then can directly access the post data without having to given them a special prefix. You could do this by creating a list of strings which you save the ids in as you generate them and then saving them in the view state. Of course that requires the view state to be enabled and takes up more space in the viewstate.
foreach (string uniqueId in UniqueIds)
{
bool data = Convert.ToBoolean(Request.Form[uniqueId]);
//...
}
Your post is a little vague. It would help to see how you're adding controls to the table. Is it an ASP:Table or a regular HTML table (presumably with a runat="server" attribute since you've successfully added items to it)?
If you intend to let the user make a bunch of selections, then hit a "Submit" button, whereupon you'll process each row based on which row is checked, then you should not be handling the CheckChanged event. Otherwise, as you've noticed, you'll be causing a postback each time and it won't process any of the other checkboxes. So when you create the CheckBox do not set the eventhandler so it doesn't cause a postback.
In your submit button's eventhandler you would loop through each table row, cell, then determine whether the cell's children control contained a checkbox.
I would suggest not using a table. From what you're describing perhaps a GridView or DataList is a better option.
EDIT: here's a simple example to demonstrate. You should be able to get this working in a new project to test out.
Markup
<form id="form1" runat="server">
<div>
<table id="tbl" runat="server"></table>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
</div>
</form>
Code-behind
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
var row = new HtmlTableRow();
var cell = new HtmlTableCell();
cell.InnerText = "Row: " + i.ToString();
row.Cells.Add(cell);
cell = new HtmlTableCell();
CheckBox chk = new CheckBox() { ID = "chk" + i.ToString() };
cell.Controls.Add(chk);
row.Cells.Add(cell);
tbl.Rows.Add(row);
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (HtmlTableRow row in tbl.Rows)
{
foreach (HtmlTableCell cell in row.Cells)
{
foreach (Control c in cell.Controls)
{
if (c is CheckBox)
{
// do your processing here
CheckBox chk = c as CheckBox;
if (chk.Checked)
{
Response.Write(chk.ID + " was checked <br />");
}
}
}
}
}
}
What about using the CheckBoxList control? I have no Visual Studio open now, but as far as I remember it is a DataBound control, providing DataSource and DataBind() where you can provide a list at runtime. When the page does a postback you can traverse the list by calling something like myCheckBoxList.Items and check whether the current item is selected by calling ListItem.Selected method. This should work.
Add them in an override of the CreateChildControls method of the Page. Be sure to give them an ID! This way they get added to the control tree at the correct time.
IMHO The best way would be to use DataBound Templated Control though, i.e. something like a ListView (in .NET 3.5). then in pageload after postback traverse all items in the databound control and use item.FindControl to get at the actual checkbox.
What I ended up doing was tagging all my ID's with a know prefix and stuffing this at the top of Form_Load:
foreach (string v in this.Request.Form.AllKeys)
{
if (v.StartsWith(Prefix))
{
var data = v.Substring(Prefix.Length);
}
}
everything else seems to run to late.