Search Results

Search found 236 results on 10 pages for 'findcontrol'.

Page 4/10 | < Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >

  • Masked Edit extender inside a Repeater

    - by Viswa
    How can i dynamically create a textBox and a Masked Edit extender inside a Panel. My code is something like this: In the ASPX page: In the Aspx.cs page Private DataView Function1() { Dataview dv =new dataview(); return dv; } Private void ShowProducts_OntemDataBound(object sender, RepeaterEventItem e) { //Consider For the First Iteration of the Repeater I am Creating a Simple Text Box Dynamically Textbox txt = new textbox(); txt.Text = "8888888888"; txt.Id = "TextBox1"; //Consider For the Second Iteration of the Repeater I am Creating another TextBox and a Textbox txt1 = new textBox(); txt1.text="2223334444"; txt1.Id = "TextBox2"; MaskedEditExtender mskEdit = (MaskedEditExtender)e.Item.FindControl("MskEdit"); mskEdit.TargetControlId = txt1.Id; Panel panel1 = (Panel)e.item.Findcontrol("Panel1"); panel1.Controls.Add(txt1); } When running the above code it is giving me "Null Reference Exception for MaskedEditExtender".Please suggest me some way for this.

    Read the article

  • How do I retrieve the values entered in a nested control added dynamically to a webform?

    - by Front Runner
    I have a date range user control with two calendar controls: DateRange.ascx public partial class DateRange { public string FromDate { get { return calFromDate.Text; } set { calFromDate.Text = value; } } public string ToDate { get { return calToDate.Date; } set { calToDate.Text = value; } } } I have another user control in which DateRange control is loaded dynamically: ParamViewer.ascx public partial class ParamViewer { public void Setup(string sControlName) { //Load parameter control Control control = LoadControl("DateRange.ascx"); Controls.Add(control); DateRange dteFrom = (DateRange)control.FindControl("calFromDate"); DateRange dteTo = (DateRange)control.FindControl("calToDate"); } } I have a main page webForm1.aspx where ParamViewer.ascx is added When user enter the dates, they're set correctly in DateRange control. My question is how how do I retrieve the values entered in DateRange (FromDate and ToDate)control from btnSubmit_Click event in webForm1? Please advise. Thank you in advance.

    Read the article

  • How to access drop down list from EditItemTemplate of FormView

    - by IrfanRaza
    Hello friends, I have a formview on my aspx page containing various controls arranged using table. There is a DDL "cboClients" which i need to enable or disabled depending upon role within Edit mode. The problem here is that i am not able to get that control using FindControl() method. I have tried following code - DropDownList ddl = null; if (FormView1.Row != null) { ddl = (DropDownList)FormView1.Row.FindControl("cboClients"); ddl.Enabled=false; } Even I ave used the DataBound event of the same control - protected void cboClients_DataBound(object sender, EventArgs e) { if (FormView1.CurrentMode == FormViewMode.Edit) { if ((Session["RoleName"].ToString().Equals("Clients")) || (Session["RoleName"].ToString().Equals("Suppliers"))) { DropDownList ddl = (DropDownList)sender; ddl.Enabled = false; } } } But this databound event occurs only once, but not when formview mode is changed. Can anyone provide me proper solution? Thanks for sharing your time.

    Read the article

  • Eval ID on radiobutton in Datalist

    - by ravi
    my code gota datalist with radio button and iv made it single selectable onitemdatabound....now im trying to evaluate a hiddenfield on basis of selected radio button my code goes like this aspx code <asp:DataList ID="DataList1" runat="server" RepeatColumns = "4" CssClass="datalist1" RepeatLayout = "Table" OnItemDataBound="SOMENAMEItemBound" CellSpacing="20" onselectedindexchanged="DataList1_SelectedIndexChanged"> <ItemTemplate> <br /> <table cellpadding = "5px" cellspacing = "0" class="dlTable"> <tr> <td align="center"> <a href="<%#Eval("FilePath")%>" target="_blank"><asp:Image ID="Image1" runat="server" CssClass="imu" ImageUrl = '<%# Eval("FilePath")%>' Width = "100px" Height = "100px" style ="cursor:pointer" /> </td> </tr> <tr > <td align="center"> <asp:RadioButton ID="rdb" runat="server" OnCheckedChanged="rdb_click" AutoPostBack="True" /> <asp:HiddenField ID="HiddenField1" runat="server" Value = '<%#Eval("ID")%>' /> </td> </tr> </table> </ItemTemplate> </asp:DataList> code behind protected void SOMENAMEItemBound(object sender, DataListItemEventArgs e) { RadioButton rdb; rdb = (RadioButton)e.Item.FindControl("rdb"); if (rdb != null) rdb.Attributes.Add("onclick", "CheckOnes(this);"); } protected void rdb_click(object sender, EventArgs e) { for (int i = 0; i < DataList1.Items.Count; i++) { RadioButton rdb; rdb = (RadioButton)DataList1.Items[i].FindControl("rdb"); if (rdb != null) { if (rdb.Checked) { HiddenField hf = (HiddenField)DataList1.Items[i].FindControl("HiddenField1"); Response.Write(hf.Value); } } } } the javascript im using... function CheckOnes(spanChk){ var oItem = spanChk.children; var theBox= (spanChk.type=="radio") ? spanChk : spanChk.children.item[0]; xState=theBox.unchecked; elm=theBox.form.elements; for(i=0;i<elm.length;i++) if(elm[i].type=="radio" && elm[i].id!=theBox.id) { elm[i].checked=xState; } } iam getting an error like this Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled. Details: Error parsing near 'pload Demonstration|'. is there any other way to do this or can nyone plz help to get rid of this problem

    Read the article

  • User can't login after creating them with the asp.net Create User Wizard

    - by Xaisoft
    When I create a user, they can't login until I go into the asp.net configuration and save them. I actually don't change any settings, I just press the save button and then they can login in. What I would like to do is to have the user be able to login once they are created, but I can't seem to get it to work. Here is my code for the CreatedUser method: protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e) { CustomerProfile adminProfile = CustomerProfile.GetProfile(); string username = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("UserName")).Text.Trim(); CustomerProfile createdUser = CustomerProfile.GetProfile(username); createdUser.CustomerID = adminProfile.CustomerID; createdUser.Save(); MembershipUser user = Membership.GetUser(username); user.IsApproved = ((CheckBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("chkActivateUser")).Checked; Roles.AddUserToRole(user.UserName, "nonadmin"); }

    Read the article

  • ArgumentNullException when accessing a FormView instance

    - by David
    Background: I have an ASP.NET page which has a numebr of user controls within it. There are 2 user controls which are of interest. I need to display either one of them or neither of them, depending on the record selected previously. In the user controls I need to set properties of some controls which are in a FormView. So in my user control code-behind I have a number of properties which look something like this: Private ReadOnly Property phSectionReports() As PlaceHolder Get Return fvConfirmationReport.FindControl("phSectionReports") End Get End Property The problem: I am having problems with this Property. Sometimes it is returning Nothing/Null and sometimes it is throwing a NullArgumentException with the message "Value cannot be null. Parameter name: container". The exception is coming from trying to reference the fvConfirmationReport variable. fvConfirmationReport is the ID of my FormView in the page itself. So I am really after things to look for and if any ideas what sort of conditions (e.g stage in page cycle, etc.) might lead to this? An example stack trace is included below. ASP.NET 3.5 SP1, VB.NET Thanks, StackTrace: at System.Web.UI.DataBinder.GetPropertyValue(Object container, String propName) at System.Web.UI.WebControls.GridView.CreateChildControls(IEnumerable dataSource, Boolean dataBinding) at System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) at System.Web.UI.WebControls.GridView.PerformDataBinding(IEnumerable data) at System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) at System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) at System.Web.UI.WebControls.DataBoundControl.PerformSelect() at System.Web.UI.WebControls.BaseDataBoundControl.DataBind() at System.Web.UI.WebControls.GridView.DataBind() at System.Web.UI.Control.DataBindChildren() at System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) ...snip... at System.Web.UI.Control.DataBind() at System.Web.UI.Control.DataBindChildren() at System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) at System.Web.UI.WebControls.FormView.CreateChildControls(IEnumerable dataSource, Boolean dataBinding) at System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) at System.Web.UI.WebControls.FormView.PerformDataBinding(IEnumerable data) at System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) at System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) at System.Web.UI.WebControls.DataBoundControl.PerformSelect() at System.Web.UI.WebControls.BaseDataBoundControl.DataBind() at System.Web.UI.WebControls.FormView.DataBind() at System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() at System.Web.UI.WebControls.FormView.EnsureDataBound() at System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() at System.Web.UI.Control.EnsureChildControls() at System.Web.UI.Control.FindControl(String id, Int32 pathOffset) at System.Web.UI.Control.FindControl(String id) at App_UserControls_xxx_ucConfirmationForm.get_phSectionReports() in ucConfirmationForm.ascx.vb:line 343 at App_UserControls_xxx_ucConfirmationForm.Page_Load(Object sender, EventArgs e) in ucConfirmationForm.ascx.vb:line 412 at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() ...snip... at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

    Read the article

  • problem with dll file linked with masterpage

    - by sumit
    i have recently find the solution that how i can retrieve the fileupload id when page is linked with masterpage in codebehind as ContentPlaceHolder content = Page.Master.FindControl("ContentPlaceHolder1") as ContentPlaceHolder; Fileupload f=content.FindControl("FileUpload1") as FileUpload; in my contentplaceholeder1 i have a dropdownlist with id dropdownlist1 now i m trying to use it in one of the cs file of dll file as if (previousFields.ContainsKey("dropdownlist1")) { prefix = previousFields["dropdownlist1"]; } where dropdownload list is the previos field of fileupload so it checks the previos field and assign the prefix to the corresponding value.nw i want to know how can i access the dropdownlist id within contentplaceholder1 id

    Read the article

  • Hiding/Unhiding Control in Gridview’s column - shifting problem

    - by lupital
    This is a follow up to my previous question: link text In gridview's column i have a linkbutton and a label under it. I want to hide/unhide label when linkbutton is clicked. I use javascript because i don't want any postbacks. The code: protected void gvwComments_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { LinkButton lButton = ((LinkButton)e.Row.Cells[2].FindControl("lbtnExpand")); Label label = ((Label)e.Row.Cells[2].FindControl("lblBody")); lButton.Attributes.Add("onclick", string.Format("HideLabel('{0}'); return false;", label.ClientID)); } } function HideLabel(button) { var rowObj = document.getElementById(button); if (rowObj.style.display == "none") { rowObj.style.display = "block"; } else { rowObj.style.display = "none"; } } The problem is that when I unhide the label by clicking on button, linkbutton is shifted a a bit upper it's original position in the cell. Is it possible to preserve linkbutton's position in the gridviews cell?

    Read the article

  • How to make DropDownList automatically be selected based on the Label.Text

    - by Archana B.R
    I have a DropDownlist in the GridView, which should be visible only when edit is clicked. I have bound the DropDownList from code behind. When I click on Edit, the label value of that cell should automatically get selected in the DropDownList. The code I have tried is: protected void GridView3_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { SqlCommand cmd = new SqlCommand("SELECT Location_Name FROM Location_Table"); DropDownList bind_drop = (e.Row.FindControl("DropList") as DropDownList); bind_drop.DataSource = this.ExecuteQuery(cmd, "SELECT"); bind_drop.DataTextField = "Location_Name"; bind_drop.DataValueField = "Location_Name"; bind_drop.DataBind(); string Loc_type = (e.Row.FindControl("id2") as Label).Text.Trim(); bind_drop.Items.FindByValue(Loc_type).Selected = true; } } When I run the code, it gives an exception error Object reference not set in the last line of the above code. Cannot find out whats wrong. Kindly help

    Read the article

  • how to add values in array

    - by nhoyti
    hi guys, i just want to ask help again. I've created a method to read values in gridview, i was able to get and read values from the gridview. The problem now, is how can i store the values inside an array and i want it to pass on the other page. here's the code i've created private void getrowvalues() { string combinedvalues; foreach (GridViewRow row in gvOrderProducts.Rows) { string prodname = ((Label)row.FindControl("lblProductName")).Text; string txtvalues = ((TextBox)row.FindControl("txtQuantity")).Text; combinedvalues = prodname + "|" + txtvalues; } } i want the result string combinedvalues to be put in an array or collection of strings which i can be access in other page. Is there a way to do it? Any inputs will be greatly appreciated. thanks!!

    Read the article

  • Apply CSS class to invalid controls on web form

    - by user137639
    I need to apply a css class to invalid controls on a web form. I'd like to make it a resusable class. This is what I have so far: public class Validation { public static void ApplyInvalidClass(Page page, string className) { foreach (System.Web.UI.WebControls.BaseValidator bv in page.Validators) { if (!bv.IsValid) { Control ctrl = page.FindControl(bv.ControlToValidate); if (ctrl != null) { if (ctrl is TextBox) { TextBox txt = ctrl as TextBox; txt.CssClass = "invalid"; } if (ctrl is DropDownList) { DropDownList ddl = ctrl as DropDownList; ddl.CssClass = "invalid"; } if (ctrl is CheckBox) { CheckBox cb = ctrl as CheckBox; cb.CssClass = "invalid"; } if (ctrl is HtmlGenericControl) { HtmlGenericControl html = ctrl as HtmlGenericControl; html.Attributes.Add("class", className); } } } } } } The problem is what I call this on a .Net user control, I guess because I'm passing in Page, page.FindControl(bv.ControlToValidate) is always null. Is there a better way to do this?

    Read the article

  • How to create Custom ListForm WebPart

    - by DipeshBhanani
    Mostly all who works extensively on SharePoint (including meJ) don’t like to use out-of-box list forms (DispForm.aspx, EditForm.aspx, NewForm.aspx) as interface. Actually these OOB list forms bind hands of developers for the customization. It gives headache to developers to add just one post back event, for a dropdown field and to populate other fields in NewForm.aspx or EditForm.aspx. On top of that clients always ask such stuff. So here I am going to give you guys a flight for SharePoint Customization world. In this blog, I will explain, how to create CustomListForm WebPart. In my next blogs, I am going to explain easy deployment of List Forms through features and last, guidance on using SharePoint web controls. 1.       First thing, create a class library project through Visual Studio and inherit the class with WebPart class.     public class CustomListForm : WebPart   2.       Declare the public variables and properties which we are going to use throughout the class. You will get to know these once you see them in use.         #region "Variable Declaration"           Table spTableCntl;         FormToolBar formToolBar;         Literal ltAlertMessage;         Guid SiteId;         Guid ListId;         int ItemId;         string ListName;           #endregion           #region "Properties"           SPControlMode _ControlMode = SPControlMode.New;         [Personalizable(PersonalizationScope.Shared),          WebBrowsable(true),          WebDisplayName("Control Mode"),          WebDescription("Set Control Mode"),          DefaultValue(""),          Category("Miscellaneous")]         public SPControlMode ControlMode         {             get { return _ControlMode; }             set { _ControlMode = value; }         }           #endregion     The property “ControlMode” is used to identify the mode of the List Form. The property is of type SPControlMode which is an enum type with values (Display, Edit, New and Invalid). When we will add this WebPart to DispForm.aspx, EditForm.aspx and NewForm.aspx, we will set the WebPart property “ControlMode” to Display, Edit and New respectively.     3.       Now, we need to override the CreateChildControl method and write code to manually add SharePoint Web Controls related to each list fields as well as ToolBar controls.         protected override void CreateChildControls()         {             base.CreateChildControls();               try             {                 SiteId = SPContext.Current.Site.ID;                 ListId = SPContext.Current.ListId;                 ListName = SPContext.Current.List.Title;                   if (_ControlMode == SPControlMode.Display || _ControlMode == SPControlMode.Edit)                     ItemId = SPContext.Current.ItemId;                   SPSecurity.RunWithElevatedPrivileges(delegate()                 {                     using (SPSite site = new SPSite(SiteId))                     {                         //creating a new SPSite with credentials of System Account                         using (SPWeb web = site.OpenWeb())                         {                               //<Custom Code for creating form controls>                         }                     }                 });             }             catch (Exception ex)             {                 ShowError(ex, "CreateChildControls");             }         }   Here we are assuming that we are developing this WebPart to plug into List Forms. Hence we will get the List Id and List Name from the current context. We can have Item Id only in case of Display and Edit Mode. We are putting our code into “RunWithElevatedPrivileges” to elevate privileges to System Account. Now, let’s get deep down into the main code and expand “//<Custom Code for creating form controls>”. Before initiating any SharePoint control, we need to set context of SharePoint web controls explicitly so that it will be instantiated with elevated System Account user. Following line does the job.     //To create SharePoint controls with new web object and System Account credentials     SPControl.SetContextWeb(Context, web);   First thing, let’s add main table as container for all controls.     //Table to render webpart     Table spTableMain = new Table();     spTableMain.CellPadding = 0;     spTableMain.CellSpacing = 0;     spTableMain.Width = new Unit(100, UnitType.Percentage);     this.Controls.Add(spTableMain);   Now we need to add Top toolbar with Save and Cancel button at top as you see in the below screen shot.       // Add Row and Cell for Top ToolBar     TableRow spRowTopToolBar = new TableRow();     spTableMain.Rows.Add(spRowTopToolBar);     TableCell spCellTopToolBar = new TableCell();     spRowTopToolBar.Cells.Add(spCellTopToolBar);     spCellTopToolBar.Width = new Unit(100, UnitType.Percentage);         ToolBar toolBarTop = (ToolBar)Page.LoadControl("/_controltemplates/ToolBar.ascx");     toolBarTop.CssClass = "ms-formtoolbar";     toolBarTop.ID = "toolBarTbltop";     toolBarTop.RightButtons.SeparatorHtml = "<td class=ms-separator> </td>";       if (_ControlMode != SPControlMode.Display)     {         SaveButton btnSave = new SaveButton();         btnSave.ControlMode = _ControlMode;         btnSave.ListId = ListId;           if (_ControlMode == SPControlMode.New)             btnSave.RenderContext = SPContext.GetContext(web);         else         {             btnSave.RenderContext = SPContext.GetContext(this.Context, ItemId, ListId, web);             btnSave.ItemContext = SPContext.GetContext(this.Context, ItemId, ListId, web);             btnSave.ItemId = ItemId;         }         toolBarTop.RightButtons.Controls.Add(btnSave);     }       GoBackButton goBackButtonTop = new GoBackButton();     toolBarTop.RightButtons.Controls.Add(goBackButtonTop);     goBackButtonTop.ControlMode = SPControlMode.Display;       spCellTopToolBar.Controls.Add(toolBarTop);   Here we have use “SaveButton” and “GoBackButton” which are internal SharePoint web controls for save and cancel functionality. I have set some of the properties of Save Button with if-else condition because we will not have Item Id in case of New Mode. Item Id property is used to identify which SharePoint List Item need to be saved. Now, add Form Toolbar to the page which contains “Attach File”, “Delete Item” etc buttons.       // Add Row and Cell for FormToolBar     TableRow spRowFormToolBar = new TableRow();     spTableMain.Rows.Add(spRowFormToolBar);     TableCell spCellFormToolBar = new TableCell();     spRowFormToolBar.Cells.Add(spCellFormToolBar);     spCellFormToolBar.Width = new Unit(100, UnitType.Percentage);       FormToolBar formToolBar = new FormToolBar();     formToolBar.ID = "formToolBar";     formToolBar.ListId = ListId;     if (_ControlMode == SPControlMode.New)         formToolBar.RenderContext = SPContext.GetContext(web);     else     {         formToolBar.RenderContext = SPContext.GetContext(this.Context, ItemId, ListId, web);         formToolBar.ItemContext = SPContext.GetContext(this.Context, ItemId, ListId, web);         formToolBar.ItemId = ItemId;     }     formToolBar.ControlMode = _ControlMode;     formToolBar.EnableViewState = true;       spCellFormToolBar.Controls.Add(formToolBar);     The ControlMode property will take care of which button to be displayed on the toolbar. E.g. “Attach files”, “Delete Item” in new/edit forms and “New Item”, “Edit Item”, “Delete Item”, “Manage Permissions” etc in display forms. Now add main section which contains form field controls.     //Create Form Field controls and add them in Table "spCellCntl"     CreateFieldControls(web);     //Add public variable "spCellCntl" containing all form controls to the page     spRowCntl.Cells.Add(spCellCntl);     spCellCntl.Width = new Unit(100, UnitType.Percentage);     spCellCntl.Controls.Add(spTableCntl);       //Add a Blank Row with height of 5px to render space between ToolBar table and Control table     TableRow spRowLine1 = new TableRow();     spTableMain.Rows.Add(spRowLine1);     TableCell spCellLine1 = new TableCell();     spRowLine1.Cells.Add(spCellLine1);     spCellLine1.Height = new Unit(5, UnitType.Pixel);     spCellLine1.Controls.Add(new LiteralControl("<IMG SRC='/_layouts/images/blank.gif' width=1 height=1 alt=''>"));       //Add Row and Cell for Form Controls Section     TableRow spRowCntl = new TableRow();     spTableMain.Rows.Add(spRowCntl);     TableCell spCellCntl = new TableCell();       //Create Form Field controls and add them in Table "spCellCntl"     CreateFieldControls(web);     //Add public variable "spCellCntl" containing all form controls to the page     spRowCntl.Cells.Add(spCellCntl);     spCellCntl.Width = new Unit(100, UnitType.Percentage);     spCellCntl.Controls.Add(spTableCntl);       TableRow spRowLine2 = new TableRow();     spTableMain.Rows.Add(spRowLine2);     TableCell spCellLine2 = new TableCell();     spRowLine2.Cells.Add(spCellLine2);     spCellLine2.CssClass = "ms-formline";     spCellLine2.Controls.Add(new LiteralControl("<IMG SRC='/_layouts/images/blank.gif' width=1 height=1 alt=''>"));       // Add Blank row with height of 5 pixel     TableRow spRowLine3 = new TableRow();     spTableMain.Rows.Add(spRowLine3);     TableCell spCellLine3 = new TableCell();     spRowLine3.Cells.Add(spCellLine3);     spCellLine3.Height = new Unit(5, UnitType.Pixel);     spCellLine3.Controls.Add(new LiteralControl("<IMG SRC='/_layouts/images/blank.gif' width=1 height=1 alt=''>"));   You can add bottom toolbar also to get same look and feel as OOB forms. I am not adding here as the blog will be much lengthy. At last, you need to write following lines to allow unsafe updates for Save and Delete button.     // Allow unsafe update on web for save button and delete button     if (this.Page.IsPostBack && this.Page.Request["__EventTarget"] != null         && (this.Page.Request["__EventTarget"].Contains("IOSaveItem")         || this.Page.Request["__EventTarget"].Contains("IODeleteItem")))     {         SPContext.Current.Web.AllowUnsafeUpdates = true;     }   So that’s all. We have finished writing Custom Code for adding field control. But something most important is skipped. In above code, I have called function “CreateFieldControls(web);” to add SharePoint field controls to the page. Let’s see the implementation of the function:     private void CreateFieldControls(SPWeb pWeb)     {         SPList listMain = pWeb.Lists[ListId];         SPFieldCollection fields = listMain.Fields;           //Main Table to render all fields         spTableCntl = new Table();         spTableCntl.BorderWidth = new Unit(0);         spTableCntl.CellPadding = 0;         spTableCntl.CellSpacing = 0;         spTableCntl.Width = new Unit(100, UnitType.Percentage);         spTableCntl.CssClass = "ms-formtable";           SPContext controlContext = SPContext.GetContext(this.Context, ItemId, ListId, pWeb);           foreach (SPField listField in fields)         {             string fieldDisplayName = listField.Title;             string fieldInternalName = listField.InternalName;               //Skip if the field is system field or hidden             if (listField.Hidden || listField.ShowInVersionHistory == false)                 continue;               //Skip if the control mode is display and field is read-only             if (_ControlMode != SPControlMode.Display && listField.ReadOnlyField == true)                 continue;               FieldLabel fieldLabel = new FieldLabel();             fieldLabel.FieldName = listField.InternalName;             fieldLabel.ListId = ListId;               BaseFieldControl fieldControl = listField.FieldRenderingControl;             fieldControl.ListId = ListId;             //Assign unique id using Field Internal Name             fieldControl.ID = string.Format("Field_{0}", fieldInternalName);             fieldControl.EnableViewState = true;               //Assign control mode             fieldLabel.ControlMode = _ControlMode;             fieldControl.ControlMode = _ControlMode;             switch (_ControlMode)             {                 case SPControlMode.New:                     fieldLabel.RenderContext = SPContext.GetContext(pWeb);                     fieldControl.RenderContext = SPContext.GetContext(pWeb);                     break;                 case SPControlMode.Edit:                 case SPControlMode.Display:                     fieldLabel.RenderContext = controlContext;                     fieldLabel.ItemContext = controlContext;                     fieldLabel.ItemId = ItemId;                       fieldControl.RenderContext = controlContext;                     fieldControl.ItemContext = controlContext;                     fieldControl.ItemId = ItemId;                     break;             }               //Add row to display a field row             TableRow spCntlRow = new TableRow();             spTableCntl.Rows.Add(spCntlRow);               //Add the cells for containing field lable and control             TableCell spCellLabel = new TableCell();             spCellLabel.Width = new Unit(30, UnitType.Percentage);             spCellLabel.CssClass = "ms-formlabel";             spCntlRow.Cells.Add(spCellLabel);             TableCell spCellControl = new TableCell();             spCellControl.Width = new Unit(70, UnitType.Percentage);             spCellControl.CssClass = "ms-formbody";             spCntlRow.Cells.Add(spCellControl);               //Add the control to the table cells             spCellLabel.Controls.Add(fieldLabel);             spCellControl.Controls.Add(fieldControl);               //Add description if there is any in case of New and Edit Mode             if (_ControlMode != SPControlMode.Display && listField.Description != string.Empty)             {                 FieldDescription fieldDesc = new FieldDescription();                 fieldDesc.FieldName = fieldInternalName;                 fieldDesc.ListId = ListId;                 spCellControl.Controls.Add(fieldDesc);             }               //Disable Name(Title) in Edit Mode             if (_ControlMode == SPControlMode.Edit && fieldDisplayName == "Name")             {                 TextBox txtTitlefield = (TextBox)fieldControl.Controls[0].FindControl("TextField");                 txtTitlefield.Enabled = false;             }         }         fields = null;     }   First of all, I have declared List object and got list fields in field collection object called “fields”. Then I have added a table for the container of all controls and assign CSS class as "ms-formtable" so that it gives consistent look and feel of SharePoint. Now it’s time to navigate through all fields and add them if required. Here we don’t need to add hidden or system fields. We also don’t want to display read-only fields in new and edit forms. Following lines does this job.             //Skip if the field is system field or hidden             if (listField.Hidden || listField.ShowInVersionHistory == false)                 continue;               //Skip if the control mode is display and field is read-only             if (_ControlMode != SPControlMode.Display && listField.ReadOnlyField == true)                 continue;   Let’s move to the next line of code.             FieldLabel fieldLabel = new FieldLabel();             fieldLabel.FieldName = listField.InternalName;             fieldLabel.ListId = ListId;               BaseFieldControl fieldControl = listField.FieldRenderingControl;             fieldControl.ListId = ListId;             //Assign unique id using Field Internal Name             fieldControl.ID = string.Format("Field_{0}", fieldInternalName);             fieldControl.EnableViewState = true;               //Assign control mode             fieldLabel.ControlMode = _ControlMode;             fieldControl.ControlMode = _ControlMode;   We have used “FieldLabel” control for displaying field title. The advantage of using Field Label is, SharePoint automatically adds red star besides field label to identify it as mandatory field if there is any. Here is most important part to understand. The “BaseFieldControl”. It will render the respective web controls according to type of the field. For example, if it’s single line of text, then Textbox, if it’s look up then it renders dropdown. Additionally, the “ControlMode” property tells compiler that which mode (display/edit/new) controls need to be rendered with. In display mode, it will render label with field value. In edit mode, it will render respective control with item value and in new mode it will render respective control with empty value. Please note that, it’s not always the case when dropdown field will be rendered for Lookup field or Choice field. You need to understand which controls are rendered for which list fields. I am planning to write a separate blog which I hope to publish it very soon. Moreover, we also need to assign list field specific properties like List Id, Field Name etc to identify which SharePoint List field is attached with the control.             switch (_ControlMode)             {                 case SPControlMode.New:                     fieldLabel.RenderContext = SPContext.GetContext(pWeb);                     fieldControl.RenderContext = SPContext.GetContext(pWeb);                     break;                 case SPControlMode.Edit:                 case SPControlMode.Display:                     fieldLabel.RenderContext = controlContext;                     fieldLabel.ItemContext = controlContext;                     fieldLabel.ItemId = ItemId;                       fieldControl.RenderContext = controlContext;                     fieldControl.ItemContext = controlContext;                     fieldControl.ItemId = ItemId;                     break;             }   Here, I have separate code for new mode and Edit/Display mode because we will not have Item Id to assign in New Mode. We also need to set CSS class for cell containing Label and Controls so that those controls get rendered with SharePoint theme.             spCellLabel.CssClass = "ms-formlabel";             spCellControl.CssClass = "ms-formbody";   “FieldDescription” control is used to add field description if there is any.    Now it’s time to add some more customization,               //Disable Name(Title) in Edit Mode             if (_ControlMode == SPControlMode.Edit && fieldDisplayName == "Name")             {                 TextBox txtTitlefield = (TextBox)fieldControl.Controls[0].FindControl("TextField");                 txtTitlefield.Enabled = false;             }   The above code will disable the title field in edit mode. You can add more code here to achieve more customization according to your requirement. Some of the examples are as follow:             //Adding post back event on UserField to auto populate some other dependent field             //in new mode and disable it in edit mode             if (_ControlMode != SPControlMode.Display && fieldDisplayName == "Manager")             {                 if (fieldControl.Controls[0].FindControl("UserField") != null)                 {                     PeopleEditor pplEditor = (PeopleEditor)fieldControl.Controls[0].FindControl("UserField");                     if (_ControlMode == SPControlMode.New)                         pplEditor.AutoPostBack = true;                     else                         pplEditor.Enabled = false;                 }             }               //Add JavaScript Event on Dropdown field. Don't forget to add the JavaScript function on the page.             if (_ControlMode == SPControlMode.Edit && fieldDisplayName == "Designation")             {                 DropDownList ddlCategory = (DropDownList)fieldControl.Controls[0];                 ddlCategory.Attributes.Add("onchange", string.Format("javascript:DropdownChangeEvent('{0}');return false;", ddlCategory.ClientID));             }    Following are the screenshots of my Custom ListForm WebPart. Let’s play a game, check out your OOB List forms of SharePoint, compare with these screens and find out differences.   DispForm.aspx:   EditForm.aspx:   NewForm.aspx:   Enjoy the SharePoint Soup!!! ­­­­­­­­­­­­­­­­­­­­

    Read the article

  • Accessing Controls Within A Gridview

    - by Bunch
    Sometimes you need to access a control within a GridView, but it isn’t quite as straight forward as just using FindControl to grab the control like you can in a FormView. Since the GridView builds multiple rows the key is to specify the row. In this example there is a GridView with a control for a player’s errors. If the errors is greater than 9 the GridView should display the control (lblErrors) in red so it stands out. Here is the GridView: <asp:GridView ID="gvFielding" runat="server" DataSourceID="sqlFielding" DataKeyNames="PlayerID" AutoGenerateColumns="false" >     <Columns>         <asp:BoundField DataField="PlayerName" HeaderText="Player Name" />         <asp:BoundField DataField="PlayerNumber" HeaderText="Player Number" />         <asp:TemplateField HeaderText="Errors">             <ItemTemplate>                 <asp:Label ID="lblErrors" runat="server" Text='<%# EVAL("Errors") %>'  />             </ItemTemplate>         </asp:TemplateField>     </Columns> </asp:GridView> In the code behind you can add the code to change the label’s ForeColor property to red based on the amount of errors. In this case 10 or more errors triggers the color change. Protected Sub gvFielding_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvFielding.DataBound     Dim errorLabel As Label     Dim errors As Integer     Dim i As Integer = 0     For Each row As GridViewRow In gvFielding.Rows         errorLabel = gvFielding.Rows(i).FindControl("lblErrors")         If Not errorLabel.Text = Nothing Then             Integer.TryParse(errorLabel.Text, errors)             If errors > 9 Then                 errorLabel.ForeColor = Drawing.Color.Red             End If         End If         i += 1     Next End Sub The main points in the DataBound sub is use a For Each statement to loop through the rows and to increment the variable i so you loop through every row. That way you check each one and if the value is greater than 9 the label changes to red. The If Not errorLabel.Text = Nothing line is there as a check in case no data comes back at all for Errors. Technorati Tags: GridView,ASP.Net,VB.Net

    Read the article

  • edit row in gridview

    - by user576998
    Hi.I would like to help me with my code. I have 2 gridviews. In the first gridview the user can choose with a checkbox every row he wants. These rows are transfered in the second gridview. All these my code does them well.Now, I want to edit the quantity column in second gridview to change the value but i don't know what i must write in edit box. Here is my code: using System; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections; public partial class ShowLand : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindPrimaryGrid(); BindSecondaryGrid(); } } private void BindPrimaryGrid() { string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString; string query = "select * from Land"; SqlConnection con = new SqlConnection(constr); SqlDataAdapter sda = new SqlDataAdapter(query, con); DataTable dt = new DataTable(); sda.Fill(dt); gridview2.DataSource = dt; gridview2.DataBind(); } private void GetData() { DataTable dt; if (ViewState["SelectedRecords1"] != null) dt = (DataTable)ViewState["SelectedRecords1"]; else dt = CreateDataTable(); CheckBox chkAll = (CheckBox)gridview2.HeaderRow .Cells[0].FindControl("chkAll"); for (int i = 0; i < gridview2.Rows.Count; i++) { if (chkAll.Checked) { dt = AddRow(gridview2.Rows[i], dt); } else { CheckBox chk = (CheckBox)gridview2.Rows[i] .Cells[0].FindControl("chk"); if (chk.Checked) { dt = AddRow(gridview2.Rows[i], dt); } else { dt = RemoveRow(gridview2.Rows[i], dt); } } } ViewState["SelectedRecords1"] = dt; } private void SetData() { CheckBox chkAll = (CheckBox)gridview2.HeaderRow.Cells[0].FindControl("chkAll"); chkAll.Checked = true; if (ViewState["SelectedRecords1"] != null) { DataTable dt = (DataTable)ViewState["SelectedRecords1"]; for (int i = 0; i < gridview2.Rows.Count; i++) { CheckBox chk = (CheckBox)gridview2.Rows[i].Cells[0].FindControl("chk"); if (chk != null) { DataRow[] dr = dt.Select("id = '" + gridview2.Rows[i].Cells[1].Text + "'"); chk.Checked = dr.Length > 0; if (!chk.Checked) { chkAll.Checked = false; } } } } } private DataTable CreateDataTable() { DataTable dt = new DataTable(); dt.Columns.Add("id"); dt.Columns.Add("name"); dt.Columns.Add("price"); dt.Columns.Add("quantity"); dt.Columns.Add("total"); dt.AcceptChanges(); return dt; } private DataTable AddRow(GridViewRow gvRow, DataTable dt) { DataRow[] dr = dt.Select("id = '" + gvRow.Cells[1].Text + "'"); if (dr.Length <= 0) { dt.Rows.Add(); dt.Rows[dt.Rows.Count - 1]["id"] = gvRow.Cells[1].Text; dt.Rows[dt.Rows.Count - 1]["name"] = gvRow.Cells[2].Text; dt.Rows[dt.Rows.Count - 1]["price"] = gvRow.Cells[3].Text; dt.Rows[dt.Rows.Count - 1]["quantity"] = gvRow.Cells[4].Text; dt.Rows[dt.Rows.Count - 1]["total"] = gvRow.Cells[5].Text; dt.AcceptChanges(); } return dt; } private DataTable RemoveRow(GridViewRow gvRow, DataTable dt) { DataRow[] dr = dt.Select("id = '" + gvRow.Cells[1].Text + "'"); if (dr.Length > 0) { dt.Rows.Remove(dr[0]); dt.AcceptChanges(); } return dt; } protected void CheckBox_CheckChanged(object sender, EventArgs e) { GetData(); SetData(); BindSecondaryGrid(); } private void BindSecondaryGrid() { DataTable dt = (DataTable)ViewState["SelectedRecords1"]; gridview3.DataSource = dt; gridview3.DataBind(); } } and the source code is <asp:GridView ID="gridview2" runat="server" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource5"> <Columns> <asp:TemplateField> <HeaderTemplate> <asp:CheckBox ID="chkAll" runat="server" onclick = "checkAll(this);" AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged"/> </HeaderTemplate> <ItemTemplate> <asp:CheckBox ID="chk" runat="server" onclick = "Check_Click(this)" AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" /> <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" /> <asp:BoundField DataField="price" HeaderText="price" SortExpression="price" /> <asp:BoundField DataField="quantity" HeaderText="quantity" SortExpression="quantity" /> <asp:BoundField DataField="total" HeaderText="total" SortExpression="total" /> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource5" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Land]"></asp:SqlDataSource> <br /> </div> <div> <asp:GridView ID="gridview3" runat="server" AutoGenerateColumns = "False" DataKeyNames="id" EmptyDataText = "No Records Selected" > <Columns> <asp:BoundField DataField = "id" HeaderText = "id" /> <asp:BoundField DataField = "name" HeaderText = "name" ReadOnly="True" /> <asp:BoundField DataField = "price" HeaderText = "price" DataFormatString="{0:c}" ReadOnly="True" /> <asp:TemplateField HeaderText="quantity"> <EditItemTemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("quantity")%>'</asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("quantity") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField = "total" HeaderText = "total" DataFormatString="{0:c}" ReadOnly="True" /> <asp:CommandField ShowEditButton="True" /> </Columns> </asp:GridView> <asp:Label ID="totalLabel" runat="server"></asp:Label> <br /> </div> </form> </body> </html>

    Read the article

  • ASP.NET WebControl ITemplate child controls are null

    - by tster
    Here is what I want: I want a control to put on a page, which other developers can place form elements inside of to display the entities that my control is searching. I have the Searching logic all working. The control builds custom search fields and performs searches based on declarative C# classes implementing my SearchSpec interface. Here is what I've been trying: I've tried using ITemplate on a WebControl which implements INamingContainer I've tried implementing a CompositeControl The closest I can get to working is below. OK I have a custom WebControl [ AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal), AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal), DefaultProperty("SearchSpecName"), ParseChildren(true), ToolboxData("<{0}:SearchPage runat=\"server\"> </{0}:SearchPage>") ] public class SearchPage : WebControl, INamingContainer { [Browsable(false), PersistenceMode(PersistenceMode.InnerProperty), DefaultValue(typeof(ITemplate), ""), Description("Form template"), TemplateInstance(TemplateInstance.Single), TemplateContainer(typeof(FormContainer))] public ITemplate FormTemplate { get; set; } public class FormContainer : Control, INamingContainer{ } public Control MyTemplateContainer { get; private set; } [Bindable(true), Category("Behavior"), DefaultValue(""), Description("The class name of the SearchSpec to use."), Localizable(false)] public virtual string SearchSpecName { get; set; } [Bindable(true), Category("Behavior"), DefaultValue(true), Description("True if this is query mode."), Localizable(false)] public virtual bool QueryMode { get; set; } private SearchSpec _spec; private SearchSpec Spec { get { if (_spec == null) { Type type = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Name == SearchSpecName).First(); _spec = (SearchSpec)Assembly.GetExecutingAssembly().CreateInstance(type.Namespace + "." + type.Name); } return _spec; } } protected override void CreateChildControls() { if (FormTemplate != null) { MyTemplateContainer = new FormTemplateContainer(this); FormTemplate.InstantiateIn(MyTemplateContainer); Controls.Add(MyTemplateContainer); } else { Controls.Add(new LiteralControl("blah")); } } protected override void RenderContents(HtmlTextWriter writer) { // <snip> } protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Div; } } } public class FormTemplateContainer : Control, INamingContainer { private SearchPage parent; public FormTemplateContainer(SearchPage parent) { this.parent = parent; } } then the usage: <tster:SearchPage ID="sp1" runat="server" SearchSpecName="TestSearchSpec" QueryMode="False"> <FormTemplate> <br /> Test Name: <asp:TextBox ID="testNameBox" runat="server" Width="432px"></asp:TextBox> <br /> Owner: <asp:TextBox ID="ownerBox" runat="server" Width="427px"></asp:TextBox> <br /> Description: <asp:TextBox ID="descriptionBox" runat="server" Height="123px" Width="432px" TextMode="MultiLine" Wrap="true"></asp:TextBox> </FormTemplate> </tster:SearchPage> The problem is that in the CodeBehind, the page has members descriptionBox, ownerBox and testNameBox. However, they are all null. Furthermore, FindControl("ownerBox") returns null as does this.sp1.FindControl("ownerBox"). I have to do this.sp1.MyTemplateContainer.FindControl("ownerBox") to get the control. How can I make it so that the C# Code Behind will have the controls generated and not null in my Page_Load event so that developers can just do this: testNameBox.Text = "foo"; ownerBox.Text = "bar"; descriptionBox.Text = "baz";

    Read the article

  • listview and datalist not updating,inserting

    - by raging_boner
    Data entered in textboxes is not getting updated in database. In debug mode I see that text1 and text2 in ItemUpdating event contain the same values as they had before calling ItemUpdating. Here's my listview control: <asp:ListView ID="ListView1" runat="server" onitemediting="ListView1_ItemEditing" onitemupdating="ListView1_ItemUpdating" oniteminserting="ListView1_ItemInserting"> //LayoutTemplate removed <ItemTemplate> <asp:Label ID="Label2" runat="server" Text='<%#Eval("id")%>'></asp:Label> <asp:Label ID="Label3" runat="server" Text='<%#Eval("text1")%>'></asp:Label> <asp:LinkButton ID="LinkButton2" CommandName="Edit" runat="server">Edit</asp:LinkButton> <asp:LinkButton ID="LinkButton4" CommandName="Delete" runat="server">Delete</asp:LinkButton> </ItemTemplate> <EditItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%#Eval("id")%>'></asp:Label> <asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("text1")%>' TextMode="MultiLine" /> <asp:TextBox ID="TextBox2" runat="server" Text='<%#Eval("text2")%>' Height="100" TextMode="MultiLine" /> <asp:LinkButton ID="LinkButton1" CommandName="Update" CommandArgument='<%# Eval("id")%>' runat="server">Update</asp:LinkButton> <asp:LinkButton ID="LinkButton5" CommandName="Cancel" runat="server">Cancel</asp:LinkButton> </EditItemTemplate> <InsertItemTemplate> <asp:TextBox ID="TextBox3" runat="server" TextMode="MultiLine" Height="100"></asp:TextBox> <asp:TextBox ID="TextBox4" runat="server" Height="100" TextMode="MultiLine"></asp:TextBox> <asp:LinkButton ID="LinkButton3" runat="server">Insert</asp:LinkButton> </InsertItemTemplate> </asp:ListView> Codebehind file: protected void ListView1_ItemEditing(object sender, ListViewEditEventArgs e) { ListView1.EditIndex = e.NewEditIndex; BindList(); } protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e) { ListViewItem myItem = ListView1.Items[ListView1.EditIndex]; Label id = (Label)myItem.FindControl("Label1"); int dbid = int.Parse(id.Text); TextBox text1 = (TextBox)myItem.FindControl("Textbox1"); TextBox text2 = (TextBox)myItem.FindControl("Textbox2"); //tried to work withNewValues below, but they don't work, "null reference" error is being thrown //text1.Text = e.NewValues["text1"].ToString(); //text2.Text = e.NewValues["text2"].ToString(); //odbc connection routine removed. //i know that there should be odbc parameteres: comm = new OdbcCommand("UPDATE table SET text1 = '" + text1.Text + "', text2 = '" + text2.Text + "' WHERE id = '" + dbid + "'", connection); comm.ExecuteNonQuery(); conn.Close(); ListView1.EditIndex = -1; //here I databind ListView1 } What's wrong with updating of text1.Text, text2.Text in ItemUpdating event? Should I use e.NewValues property? If so, how to use it? Thanks in advance for any help.

    Read the article

  • Trying to convert string to datetime

    - by user1596472
    I am trying to restrict a user from entering a new record if the date requested already exits. I was trying to do a count to see if the table that the record would be placed in already has that date 1 or not 0. I have a calendar extender attached to a text box which has the date. I keep getting either a: String was not recognized as a valid DateTime. or Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.IConvertible'. depending on the different things I have tried. Here is my code. TextBox startd = (TextBox)(DetailsView1.FindControl("TextBox5")); TextBox endd = (TextBox)(DetailsView1.FindControl("TextBox7")); DropDownList lvtype = (DropDownList)(DetailsView1.FindControl("DropDownList6")); DateTime scheduledDate = DateTime.ParseExact(startd.Text, "dd/MM/yyyy", null); DateTime endDate = DateTime.ParseExact(endd.Text, "dd/MM/yyyy", null); DateTime newstartDate = Convert.ToDateTime(startd.Text); DateTime newendDate = Convert.ToDateTime(endd.Text); //foreach (DataRow row in sd.Tables[0].Rows) DateTime dt = newstartDate; while (dt <= newendDate) { //for retreiving from table Decimal sd = SelectCountDate(dt, lvtype.SelectedValue, countDate); String ndt = Convert.ToDateTime(dt).ToShortDateString(); // //start = string.CompareOrdinal(scheduledDate, ndt); // // end = string.CompareOrdinal(endDate, ndt); //trying to make say when leavetpe is greater than count 1 then throw error. if (sd > 0) { Response.Write("<script>alert('Date Already Requested');</script>"); } dt.AddDays(1); } ^^^ This version throws the: "String was not recognized as valid date type" error But if i replace the string with either of these : /*-----------------------Original------------------------------------ string scheduledDate = Convert.ToDateTime(endd).ToShortDateString(); string endDate = Convert.ToDateTime(endd).ToShortDateString(); -------------------------------------------------------------------*/ /*----------10-30--------------------------------------- DateTime scheduledDate = DateTime.Parse(startd.Text); DateTime endDate = DateTime.Parse(endd.Text); ------------------------------------------------------*/ I get the "Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.IConvertible'." error. I am just trying to stop a user from entering a record date that already exits. <InsertItemTemplate> <asp:TextBox ID="TextBox5" runat="server" Height="19px" Text='<%# Bind("lstdate", "{0:MM/dd/yyyy}") %>' Width="67px"></asp:TextBox> <asp:CalendarExtender ID="TextBox5_CalendarExtender" runat="server" Enabled="True" TargetControlID="TextBox5"> </asp:CalendarExtender> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox5" ErrorMessage="*Leave Date Required" ForeColor="Red"></asp:RequiredFieldValidator> <br /> <asp:CompareValidator ID="CompareValidator18" runat="server" ControlToCompare="TextBox7" ControlToValidate="TextBox5" ErrorMessage="Leave date cannot be after start date" ForeColor="Red" Operator="LessThanEqual" ToolTip="Must choose start date before end date"></asp:CompareValidator> </InsertItemTemplate>

    Read the article

  • listview not updating,inserting

    - by raging_boner
    Data entered in textboxes is not getting updated in database. In debug mode I see that textbox1 and textbox2 in ItemUpdating event contain the same values as they had before calling ItemUpdating. Here's my listview control: <asp:ListView ID="ListView1" runat="server" onitemediting="ListView1_ItemEditing" onitemupdating="ListView1_ItemUpdating" oniteminserting="ListView1_ItemInserting"> //LayoutTemplate removed <ItemTemplate> <td align="center" valign="top"> <asp:Label ID="Label2" runat="server" Text='<%#Eval("id")%>'></asp:Label><br /> <asp:Label ID="Label3" runat="server" Text='<%#Eval("text1")%>'></asp:Label> </td> <td> <asp:LinkButton ID="LinkButton2" CommandName="Edit" runat="server">Edit</asp:LinkButton> <asp:LinkButton ID="LinkButton4" CommandName="Delete" runat="server">Delete</asp:LinkButton> </td> </ItemTemplate> <EditItemTemplate> <td align="center" valign="top"> <asp:Label ID="Label1" runat="server" Text='<%#Eval("id")%>'></asp:Label> <asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("text1")%>' TextMode="MultiLine" /> <asp:TextBox ID="TextBox2" runat="server" Text='<%#Eval("text2")%>' Height="100" TextMode="MultiLine" /> <asp:LinkButton ID="LinkButton1" CommandName="Update" CommandArgument='<%# Eval("id")%>' runat="server">Update</asp:LinkButton> <asp:LinkButton ID="LinkButton5" CommandName="Cancel" runat="server">Cancel</asp:LinkButton> </td> </EditItemTemplate> <InsertItemTemplate> <td align="center" valign="top"> <asp:TextBox ID="TextBox3" runat="server" TextMode="MultiLine" Height="100"></asp:TextBox> <asp:TextBox ID="TextBox4" runat="server" Height="100" TextMode="MultiLine"></asp:TextBox><br/> <asp:LinkButton ID="LinkButton3" runat="server">Insert</asp:LinkButton> </td> </InsertItemTemplate> </asp:ListView> Codebehind file: protected void ListView1_ItemEditing(object sender, ListViewEditEventArgs e) { ListView1.EditIndex = e.NewEditIndex; BindList(); } protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e) { ListViewItem myItem = ListView1.Items[ListView1.EditIndex]; Label id = (Label)myItem.FindControl("Label1"); int dbid = int.Parse(id.Text); TextBox text1 = (TextBox)myItem.FindControl("Textbox1"); TextBox text2 = (TextBox)myItem.FindControl("Textbox2"); //tried to work withNewValues below, but they don't work, "null reference" error is being thrown //text1.Text = e.NewValues["text1"].ToString(); //text2.Text = e.NewValues["text2"].ToString(); //odbc connection routine removed. //i know that there should be odbc parameteres: comm = new OdbcCommand("UPDATE table SET text1 = '" + text1.Text + "', text2 = '" + text2.Text + "' WHERE id = '" + dbid + "'", connection); comm.ExecuteNonQuery(); conn.Close(); ListView1.EditIndex = -1; //here I databind ListView1 } What's wrong with updating of text1.Text, text2.Text in ItemUpdating event? Should I use e.NewValues property? If so, how to use it? Thanks in advance for any help.

    Read the article

  • Iterate over rows/checkboxes in a RadGrid

    - by ChessWhiz
    Hi, I have a Telerik RadGrid with a GridTemplateColumn that contains a checkbox, as follows: <telerik:GridTemplateColumn HeaderText="MINE" UniqueName="MyTemplateColumn"> <ItemTemplate> <asp:CheckBox id="MyCheckBox" runat="server"></asp:CheckBox> </ItemTemplate> </telerik:GridTemplateColumn> I want to set the box to be "checked" based on a value read from the database. I could handle the ItemDataBound event and read the database when each row is bound, but that results in n lookups. Instead, I want to handle DataBound, and then set all the values at once. So, in that method, I want code like this: // read all values from database first, then... foreach(var chkbox in MyRadGrid.MasterTableView.Columns.FindByUniqueName("MyTemplateColumn").FindControl("MyCheckBox")) { chkbox.Checked = oneValue; } That doesn't work, because FindControl isn't a method of GridColumn, and it won't generate an iterable list of the checkboxes. What is the correct way to iterate through the checkboxes in the template column? Thanks!

    Read the article

  • Why is the ASP Repeater.Items collection empty, when controls are on the screen?

    - by Ryan
    I have an ASP page with the following repeater: <asp:Repeater runat="server" ID="RegionRepeater" DataSourceID="SqlDataSourceRegions" EnableViewState="true"> <ItemTemplate> <tr> <td valign="top"> <b><%#Eval("description")%></b> <asp:HiddenField runat="server" ID="RegionID" Value='<%#Eval("region_id")%>'/> </td> <td> <asp:FileUpload ID="FileUpload" runat="server" Width="368px" /> </td> </tr> </ItemTemplate> </asp:Repeater> (The repeater is inside a Wizard, inside a content pane). The code behind is connected to the protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e) event. There are two items on the screen (two rows inside the table). However, when the code tries to read those items, the Items collection is empty! foreach(RepeaterItem region in RegionRepeater.Items) { // Never runs - the RegionRepeater.Items.Count = 0 FileUpload fileUpload = (FileUpload) region.FindControl("FileUpload"); String regionID = ((HiddenField)region.FindControl("RegionID")).Value; ... Why is the collection empty, when there are controls drawn on the screen? Thanks a lot for any help; this is starting to drive me nuts. (BTW: I tried adding/removing the EnableViewState="true" tag)

    Read the article

  • dynamically created radiobuttonlist

    - by Janet
    Have a master page. The content page has a list with hyperlinks containing request variables. You click on one of the links to go to the page containing the radiobuttonlist (maybe). First problem: When I get to the new page, I use one of the variables to determine whether to add a radiobuttonlist to a placeholder on the page. I tried to do it in page)_load but then couldn't get the values selected. When I played around doing it in preInit, the first time the page is there, I can't get to the page's controls. (Object reference not set to an instance of an object.) I think it has something to do with the MasterPage and page content? The controls aren't instantiated until later? (using vb by the way) Second problem: Say I get that to work, once I hit a button, can I still access the passed request variable to determine the selected item in the radiobuttonlist? Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit 'get sessions for concurrent Dim Master As New MasterPage Master = Me.Master Dim myContent As ContentPlaceHolder = CType(Page.Master.FindControl("ContentPlaceHolder1"), ContentPlaceHolder) If Request("str") = "1" Then Dim myList As dsSql = New dsSql() ''''instantiate the function to get dataset Dim ds As New Data.DataSet ds = myList.dsConSessionTimes(Request("eid")) If ds.Tables("conSessionTimes").Rows.Count > 0 Then Dim conY As Integer = 1 CType(myContent.FindControl("lblSidCount"), Label).Text = ds.Tables("conSessionTimes").Rows.Count.ToString Sorry to be so needy - but maybe someone could direct me to a page with examples? Maybe seeing it would help it make sense? Thanks....JB

    Read the article

  • Not possible to load DropDownList on FormView from code behind??

    - by tbone
    I have a UserControl, containing a FormView, containing a DropDownList. The FormView is bound to a data control. Like so: <asp:FormView ID="frmEdit" DataKeyNames="MetricCode" runat="server" DefaultMode="Edit" DataSourceID="llbDataSource" Cellpadding="0" > <EditItemTemplate> <asp:DropDownList ID="ParentMetricCode" runat="server" SelectedValue='<%# Bind("ParentMetricCode") %>' /> etc, etc I am trying to populate the DropDownList from the codebehind. If this was not contained in a FormView, I would normally just do it in the Page_Load event. However, that does not work within a FormView, as as soon as I try to do it, accessing the dropdownlist in code, ie: theListcontrol = CType(formView.FindControl(listControlName), System.Web.UI.WebControls.ListControl) ...the data binding mechansim of the FormView is invoked, which, of course, tries to bind the DropDownList to the underlying datasource, causing a *'ParentMetricCode' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value * error, since the DropDownList has not yet been populated. I tried performing the load in the DataBinding() event of the FormView, but then: theListcontrol = CType(formView.FindControl(listControlName), System.Web.UI.WebControls.ListControl) ...fails, as the FormView.Controls.Count = 0 at that point. Is this impossible? (I do not want to have to use a secondary ObjectDataSource to bind the dropdownlist to)

    Read the article

  • ASP.NET DropDownList posting ""

    - by Daniel
    I am using ASP.NET forms version 3.5 in VB I have a dropdownlist that is filled with data from a DB with a list of countries The code for the dropdown list is <label class="ob_label"> <asp:DropDownList ID="lstCountry" runat="server" CssClass="ob_forminput"> </asp:DropDownList> Country*</label> And the code that the list is Dim selectSQL As String = "exec dbo.*******************" ' Define the ADO.NET objects. Dim con As New SqlConnection(connectionString) Dim cmd As New SqlCommand(selectSQL, con) Dim reader As SqlDataReader ' Try to open database and read information. Try con.Open() reader = cmd.ExecuteReader() ' For each item, add the author name to the displayed ' list box text, and store the unique ID in the Value property. Do While reader.Read() Dim newItem As New ListItem() newItem.Text = reader("AllSites_Countries_Name") newItem.Value = reader("AllSites_Countries_Id") CType(LoginViewCart.FindControl("lstCountry"), DropDownList).Items.Add(newItem) Loop reader.Close() CType(LoginViewCart.FindControl("lstCountry"), DropDownList).SelectedValue = 182 Catch Err As Exception Response.Redirect("~/error-on-page/") MailSender.SendMailMessage("*********************", "", "", OrangeBoxSiteId.SiteName & " Error Catcher", "<p>Error in sub FillCountry</p><p>Error on page:" & HttpContext.Current.Request.Url.AbsoluteUri & "</p><p>Error details: " & Err.Message & "</p>") Response.Redirect("~/error-on-page/") Finally con.Close() End Try When the form is submitted an error occurs which says that the string "" cannot be converted to the datatype integer. For some reason the dropdownlist is posting "" rather than the value for the selected country.

    Read the article

  • Dynamic Control loading at wrong time?

    - by Telos
    This one is a little... odd. Basically I have a form I'm building using ASP.NET Dynamic Data, which is going to utilize several custom field templates. I've just added another field to the FormView, with it's own custom template, and the form is loading that control twice for no apparent reason. Worse yet, the first time it loads the template, the Row is not ready yet and I get the error message: {"Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control."} I'm accessing the Row variable in a LinqDataSource OnSelected event in order to get the child object... Now for the wierd part: If I reorder the fields a little, the one causing the problem no longer gets loaded twice. Any thoughts? EDIT: I've noticed that Page_Load gets called on the first load (when Row throws an exception if you try to use it) but does NOT get called the second time around. If that helps any... Right now managing it by just catching and ignoring the exception, but still a little worried that things will break if I don't find the real cause. EDIT 2: I've traced the problem to using FindControl recursively to find other controls on the page. Apparently FindControl can cause the page lifecycle events (at least up to page_load) to fire... and this occurs before that page "should" be loading so it's dynamic data "stuff" isn't ready yet.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >