Search Results

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

Page 9/10 | < Previous Page | 5 6 7 8 9 10  | Next Page >

  • itearation through gridview

    - by user1405508
    I want to get cell value from gridview,but empty string is returned .I am implemented code in selectedindexchanged event of radiobuttonlist .I iterate through gridview and access cell by code .but problem is stll remaining.I used three itemtemplate ,each has one elemnt so that each element get its own coulmn .aspx <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" > <Columns> <asp:Label ID="Label2" runat="server" Text='<%# Eval("qno") %>'> </asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:Label ID="Label3" runat="server" Text='<%# Eval("description") %>'> </ItemTemplate> </asp:TemplateField> <asp:RadioButtonList ID="RadioButtonList1" RepeatDirection="Horizontal" runat="server" OnSelectedIndexChanged="changed" AutoPostBack="true" > <asp:ListItem Value="agree" Selected="True" > </asp:ListItem> <asp:ListItem Value="disagree"> </asp:ListItem> <asp:ListItem Value="strongagree"> </asp:ListItem> <asp:ListItem Value="strondisagree"> </asp:ListItem> </asp:RadioButtonList> </Columns> </asp:GridView> <asp:Label ID="Labe11" runat="server" ></asp:Label> Code behind: public void changed(object sender, EventArgs e) { for(int i=0;i<GridView2.Rows.Count;i++) { string labtext; RadioButtonList list = GridView2.Rows[i].Cells[2].FindControl("RadioButtonList1") as RadioButtonList; labtext= GridView2.Rows[i].Cells[0].Text; Label1.Text = labtext; } }

    Read the article

  • Web Control added in .master control type not found in child page

    - by turtle
    I have a Web Site project, and within it I have a user Web Control defined in an ascx file. The control is added to the Site.Master, and it shows up correctly on the page and everything is fine. I need to override some of the control's fields on one of the pages that derive from Site.Master. // In OnLoad: MyControlName control = (MyControlName) Page.Master.GetBaseMasterPage().FindControl("controlID")); The issue is that MyControlName doesn't register as a valid Type on the child page. If I add a second instance of the control to the child page directly, the above works as needed, but if the control isn't placed directly on the page, and instead is only defined in the master page, the type is undefined. The control is not in a namespace, and is defined within the project, so I don't know why it is having such an issue location the appropriate type. If I put a breakpoint in the OnLoad, the type listed for the control is ASP.my_control_name_ascx, but using that does not work either. Why can't the child class reference the correct type? Can I fix this? Thanks!

    Read the article

  • ArgumentOutOfRangeException was unhandled by user code - (ASP .net)

    - by ASr..
    I use a GridView to display the records from the database. Also i've attached a Hyperlink to the GridView using TemplateField. When I try to add "onclick" attribute to the HyperLink inside the RowDateBound event, I get the following error.. GridView1.DataKeys[e.Row.RowIndex].Value = 'GridView1.DataKeys[e.Row.RowIndex]' threw an exception of type 'System.ArgumentOutOfRangeException' Message = "Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index" This is the coding inside the RowDataBound mentod.. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { HyperLink HyperLink1 = (HyperLink)e.Row.FindControl("HyperLink1"); //The following line makes the error HyperLink1.Attributes.Add("onclick", "ShowMyModalPopup('" + GridView1.DataKeys[e.Row.RowIndex].Value + "')"); } } This is "ShowMyModalPopup" function in javascript <script type="text/javascript"> function ShowMyModalPopup(userpk) { var modal = $find('ModalPopupExtender1'); modal.show(); WebService.FetchOneUser(userpk,DisplayResult); } </script> Can anyone please explain me why this error occurs.. Many thanks in advance..

    Read the article

  • how to bind a list to a dropdown list in gridview

    - by user3721173
    I have a GridView that it contain a Drop-down list.I have a list that wanna to bind this list to drop-down in gridview. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowDataBound="GridView1_RowDataBound"> <Columns> <ItemTemplate> <asp:Label ID="Label2" runat="server"></asp:Label> <asp:DropDownList ID="DropDownList3" runat="server" AppendDataBoundItems="True" OnSelectedIndexChanged="DropDownList3_SelectedIndexChanged1" > </asp:DropDownList> </ItemTemplate> </asp:TemplateField> </Columns> and protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { DropDownList dropdown = (DropDownList)e.Row.FindControl("DropDownList3"); ClassDal obj = new ClassDal(); List<phone> list = obj.GetAll(); dropdown.DataTextField = "phone"; dropdown.DataValueField = "id"; dropdown.DataSource = list.ToList(); dropdown.DataBind(); } and namespace sample_table { public class ClassDal { public List<phone> GetAll() { using (PracticeDBEntities1 context = new PracticeDBEntities1()) { return context.phone.ToList(); } } } } but i received this exception :Object reference not set to an instance of an object on the row: dropdown.DataTextField = "phone";

    Read the article

  • ASP.Net - Help with datagrid/checkboxes/double submit

    - by Gareth D
    We have a simple datagrid. Each row has a checkbox. The checkbox is set to autopostback, and the code-behind has an event handler for the checkbox check-changed event. This all works as expected, nothing complicated. However, we want to disable the checkboxes as soon as one is checked to prevent a double submit i.e. check box checked, all checkboxes are disabled via client side javascript, form submitted. To achieve this I we are injecting some code into the onclick event as follows (note that the alert is just for testing!): Protected Sub DgAccounts_ItemCreated(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DgAccounts.ItemCreated If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then Dim chk As CheckBox = CType(e.Item.FindControl("chkItemChecked"), CheckBox) chk.Attributes.Add("onclick", "alert('fired ...');DisableAllDataGridCheckBoxes();") End If End Sub When inspecting the source of the rendered page we get the following: <input id="DgAccounts__ctl2_chkItemChecked" type="checkbox" name="DgAccounts:_ctl2:chkItemChecked" onclick="alert('fired ...');DisableAllDataGridCheckBoxes();setTimeout('__doPostBack(\'DgAccounts$_ctl2$chkItemChecked\',\'\')', 0)" language="javascript" /> It all appears in order, however the server side event does not fire – I believe this is due to the checkbox being disabled, as if we just leave the alert in and remove the call to disable the checkbox it all works fine. Can I force the check-changed event to fire even though the check box is disabled?

    Read the article

  • How do I refer to a windows form control by name (C# / VB)

    - by Alex
    Suppose I have a label control on a windows form called "UserName". How can I refer to that label programmatically using the label name? For example I can do: For each ctrl as Control in TabPage.Controls If ctrl.Name = "UserName" Then ' Do something End If Next This seems quite inefficient. I would like to do something like: TabPage.Controls("UserName").Text = "Something" I did some googling but couldn't find a satisfactory answer. Most suggested looping, some said .NET 2005 doesn't support direct refenece using string name, and FindControl method was asp.net only... EDIT Thanks for the response so far. Here is a bit more detail. I have a windows form with three tabpages, all of which a very similar in design and function i.e. same drop down menus, labels, react in simlar way to events etc. Rather than write code for each event per tabpage I have built a class that controls the events etc. per tabpage. For example, on each tabpage there is a Label called "RecordCounter" that simply shows the number of rows in the datagridview when it is populated by selection of a variable in a drop down menu. So what I want to be able to do is, upon selection of a variable in the drop down menu, the datagridview populates itself with data, and then I simply want to display the number of rows in a label ("RecordCounter"). This is exactly the same process on each tabpage so what I am doing is passing the tabpage to the class and then I want to be able to refer to the "RecordCounter" and then update it. In my class I set the ActivePage property to be the TabPage that the user has selected and then want to be able to do something like: ActivePage.RecordCounter.Text = GetNumberOfRows()

    Read the article

  • Button inside a repeater with dropdownlist

    - by TheAlbear
    I have a repeater with a literal, a dropdown list, and a button. <asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="rep_ItemDataBound" onitemcommand="Repeater1_ItemCommand"> <ItemTemplate> <div class="buypanel"> <ul> <li>Choose finish <asp:DropDownList ID="ddlFinish" runat="server"></asp:DropDownList></li> <li>Qty <asp:Literal ID="ltQty" runat="server"></asp:Literal></li> <li><asp:Button ID="butBuy" runat="server" Text="Button" /></li> </ul> </div> </ItemTemplate> </asp:Repeater> I am binding all the information in the code behind like protected void rep_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { Products product = (Products) e.Item.DataItem; //Dropdownlist to be bound. //Set Buy Button var butBuy = (Button) e.Item.FindControl("butBuy"); butBuy.CommandName = "Buy"; butBuy.CommandArgument = product.Id.ToString(); } } and i have my itemcommand to pick up on the button click protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e) { if(e.CommandName == "Buy") { } } I am not sure how, with a given button click, to pickup the right information from the text box and dropdown list which is along side it?

    Read the article

  • Cast exception being generated when using the same type of object

    - by David Tunnell
    I was previously using static variables to hold variable data that I want to save between postbacks. I was having problems and found that the data in these variables is lost when the appdomain ends. So I did some research and decided to go with ViewStates: static Dictionary<string, linkButtonObject> linkButtonDictonary; protected void Page_Load(object sender, EventArgs e) { if (ViewState["linkButtonDictonary"] != null) { linkButtonDictonary = (Dictionary<string, linkButtonObject>)ViewState["linkButtonDictonary"]; } else { linkButtonDictonary = new Dictionary<string, linkButtonObject>(); } } And here is the very simple class I use: [Serializable] public class linkButtonObject { public string storyNumber { get; set; } public string TaskName { get; set; } } I am adding to linkButtonDictionary as a gridview is databound: protected void hoursReportGridView_OnRowDataBound(Object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { LinkButton btn = (LinkButton)e.Row.FindControl("taskLinkButton"); linkButtonObject currentRow = new linkButtonObject(); currentRow.storyNumber = e.Row.Cells[3].Text; currentRow.TaskName = e.Row.Cells[5].Text; linkButtonDictonary.Add(btn.UniqueID, currentRow); } } It appears that my previous issues are resolved however a new one has arisin. Sometime when I postback I am getting this error: [A]System.Collections.Generic.Dictionary2[System.String,linkButtonObject] cannot be cast to [B]System.Collections.Generic.Dictionary2[System.String,linkButtonObject]. Type A originates from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'LoadNeither' at location 'C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'. Type B originates from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'LoadNeither' at location 'C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'. I don't understand how there can be a casting issue when I am using the same class everywhere. What am I doing wrong and how do I fix it?

    Read the article

  • Enabling all buttons in a repeater except for the clicked one

    - by NewAmbition
    I have a Repeater Control with various buttons in it. When the button gets clicked, it needs to disable itself so it cant be clicked again. Working. However, when I click that button, it needs to enable any other button but it. So, When I click on it, it needs to disable. When I click on another one, the previous button must enable, and that one must disable. So for I've tried: Button btnLoad = (Button)e.Item.FindControl("btnLoad"); foreach (Button b in e.Item.Controls.OfType<Button>().Select(c => c).Where(b => b != btnLoad)) { b.Enabled = true; } btnLoad.Text = "Currently Viewing"; btnLoad.Enabled = false; But it isnt working. Depending on where I put it, its either leaving all the buttons enabled (But still changing its text), or not doing anything at all. What do I need to do to make this work?

    Read the article

  • Disable a control inside a gridview

    - by saeed talaee
    Hi i want to disable link-bottoms control in a grid view with the condition of a special value . for example if the count for a row become 0 ,the link bottom for that row should be invisible . what should i do? where should i write the code? here is cod that i write in row command grid view but it works only of i push the link bottom!! but i want to apply this cod to my page before loading. please guide me int idx = Convert.ToInt32(e.CommandArgument); idx = idx - (GridView1.PageSize * GridView1.PageIndex); int ID = (int)GridView1.DataKeys[idx].Value; string connStr = ConfigurationManager.ConnectionStrings["dbconn"].ConnectionString; SqlConnection sqlconn = new SqlConnection(connStr); SqlCommand sqlcmd = new SqlCommand(); sqlcmd = new SqlCommand("SELECT count(ID) FROM ReviwerArticle where ArticleID=@ArticleID", sqlconn); sqlcmd.Parameters.AddWithValue("@ArticleID", ID); sqlconn.Open(); int count = ((int)sqlcmd.ExecuteScalar()); sqlconn.Close(); if (count == 0) { ((LinkButton)GridView1.Rows[idx].Cells[0].FindControl("LinkButton4") as LinkButton).Visible = false; }

    Read the article

  • Could not load type 'Default.DataMatch' in DataMatch.aspx file

    - by salvationishere
    I am developing a C# VS 2008 / SQL Server 2008 website, but now I am getting the above error when I build it. I included the Default.aspx, Default.aspx.cs, DataMatch.aspx, and DataMatch.aspx.cs files below. What do I need to do to fix this? Default.aspx: <%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %> ... DataMatch.aspx: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataMatch.aspx.cs" Inherits="_Default.DataMatch" %> ... Default.aspx.cs: using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Collections.Generic; using System.IO; using System.Drawing; using System.ComponentModel; using System.Data.SqlClient; using ADONET_namespace; using System.Security.Principal; //using System.Windows; public partial class _Default : System.Web.UI.Page //namespace AddFileToSQL { //protected System.Web.UI.HtmlControls.HtmlInputFile uploadFile; //protected System.Web.UI.HtmlControls.HtmlInputButton btnOWrite; //protected System.Web.UI.HtmlControls.HtmlInputButton btnAppend; protected System.Web.UI.WebControls.Label Label1; protected static string inputfile = ""; public static string targettable; public static string selection; // Number of controls added to view state protected int default_NumberOfControls { get { if (ViewState["default_NumberOfControls"] != null) { return (int)ViewState["default_NumberOfControls"]; } else { return 0; } } set { ViewState["default_NumberOfControls"] = value; } } protected void uploadFile_onclick(object sender, EventArgs e) { } protected void Load_GridData() { //GridView1.DataSource = ADONET_methods.DisplaySchemaTables(); //GridView1.DataBind(); } protected void btnOWrite_Click(object sender, EventArgs e) { if (uploadFile.PostedFile.ContentLength > 0) { feedbackLabel.Text = "You do not have sufficient access to overwrite table records."; } else { feedbackLabel.Text = "This file does not contain any data."; } } protected void btnAppend_Click(object sender, EventArgs e) { string fullpath = Page.Request.PhysicalApplicationPath; string path = uploadFile.PostedFile.FileName; if (File.Exists(path)) { // Create a file to write to. try { StreamReader sr = new StreamReader(path); string s = ""; while (sr.Peek() > 0) s = sr.ReadLine(); sr.Close(); } catch (IOException exc) { Console.WriteLine(exc.Message + "Cannot open file."); return; } } if (uploadFile.PostedFile.ContentLength > 0) { inputfile = System.IO.File.ReadAllText(path); Session["Message"] = inputfile; Response.Redirect("DataMatch.aspx"); } else { feedbackLabel.Text = "This file does not contain any data."; } } protected void Page_Load(object sender, EventArgs e) { if (Request.IsAuthenticated) { WelcomeBackMessage.Text = "Welcome back, " + User.Identity.Name + "!"; // Reference the CustomPrincipal / CustomIdentity CustomIdentity ident = User.Identity as CustomIdentity; if (ident != null) WelcomeBackMessage.Text += string.Format(" You are the {0} of {1}.", ident.Title, ident.CompanyName); AuthenticatedMessagePanel.Visible = true; AnonymousMessagePanel.Visible = false; if (!Page.IsPostBack) { Load_GridData(); } } else { AuthenticatedMessagePanel.Visible = false; AnonymousMessagePanel.Visible = true; } } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { GridViewRow row = GridView1.SelectedRow; targettable = row.Cells[2].Text; } } DataMatch.aspx.cs: using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using ADONET_namespace; //using MatrixApp; //namespace AddFileToSQL //{ public partial class DataMatch : AddFileToSQL._Default { protected System.Web.UI.WebControls.PlaceHolder phTextBoxes; protected System.Web.UI.WebControls.PlaceHolder phDropDownLists; protected System.Web.UI.WebControls.Button btnAnotherRequest; protected System.Web.UI.WebControls.Panel pnlCreateData; protected System.Web.UI.WebControls.Literal lTextData; protected System.Web.UI.WebControls.Panel pnlDisplayData; protected static string inputfile2; static string[] headers = null; static string[] data = null; static string[] data2 = null; static DataTable myInputFile = new DataTable("MyInputFile"); static string[] myUserSelections; static bool restart = false; private DropDownList[] newcol; int @temp = 0; string @tempS = ""; string @tempT = ""; // a Property that manages a counter stored in ViewState protected int NumberOfControls { get { return (int)ViewState["NumControls"]; } set { ViewState["NumControls"] = value; } } private Hashtable ddl_ht { get { return (Hashtable)ViewState["ddl_ht"]; } set { ViewState["ddl_ht"] = value; } } // Page Load private void Page_Load(object sender, System.EventArgs e) { if (!Page.IsPostBack) { ddl_ht = new Hashtable(); this.NumberOfControls = 0; } } // This data comes from input file private void PopulateFileInputTable() { myInputFile.Columns.Clear(); string strInput, newrow; string[] oneRow; DataColumn myDataColumn; DataRow myDataRow; int result, numRows; //Read the input file strInput = Session["Message"].ToString(); data = strInput.Split('\r'); //Headers headers = data[0].Split('|'); //Data for (int i = 0; i < data.Length; i++) { newrow = data[i].TrimStart('\n'); data[i] = newrow; } result = String.Compare(data[data.Length - 1], ""); numRows = data.Length; if (result == 0) { numRows = numRows - 1; } data2 = new string[numRows]; for (int a = 0, b = 0; a < numRows; a++, b++) { data2[b] = data[a]; } // Create columns for (int col = 0; col < headers.Length; col++) { @temp = (col + 1); @tempS = @temp.ToString(); @tempT = "@col"+ @temp.ToString(); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = headers[col]; myInputFile.Columns.Add(myDataColumn); ddl_ht.Add(@tempT, headers[col]); } // Create new DataRow objects and add to DataTable. for (int r = 0; r < numRows - 1; r++) { oneRow = data2[r + 1].Split('|'); myDataRow = myInputFile.NewRow(); for (int c = 0; c < headers.Length; c++) { myDataRow[c] = oneRow[c]; } myInputFile.Rows.Add(myDataRow); } NumberOfControls = headers.Length; myUserSelections = new string[NumberOfControls]; } //Create display panel private void CreateDisplayPanel() { btnSubmit.Style.Add("top", "auto"); btnSubmit.Style.Add("left", "auto"); btnSubmit.Style.Add("position", "absolute"); btnSubmit.Style.Add("top", "200px"); btnSubmit.Style.Add("left", "400px"); newcol = CreateDropDownLists(); for (int counter = 0; counter < NumberOfControls; counter++) { pnlDisplayData.Controls.Add(newcol[counter]); pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>")); pnlDisplayData.Visible = true; pnlDisplayData.FindControl(newcol[counter].ID); } } //Recreate display panel private void RecreateDisplayPanel() { btnSubmit.Style.Add("top", "auto"); btnSubmit.Style.Add("left", "auto"); btnSubmit.Style.Add("position", "absolute"); btnSubmit.Style.Add("top", "200px"); btnSubmit.Style.Add("left", "400px"); newcol = RecreateDropDownLists(); for (int counter = 0; counter < NumberOfControls; counter++) { pnlDisplayData.Controls.Add(newcol[counter]); pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>")); pnlDisplayData.Visible = true; pnlDisplayData.FindControl(newcol[counter].ID); } } // Add DropDownList Control to Placeholder private DropDownList[] CreateDropDownLists() { DropDownList[] dropDowns = new DropDownList[NumberOfControls]; for (int counter = 0; counter < NumberOfControls; counter++) { DropDownList ddl = new DropDownList(); SqlDataReader dr2 = ADONET_methods.DisplayTableColumns(targettable); ddl.ID = "DropDownListID" + counter.ToString(); int NumControls = targettable.Length; DataTable dt = new DataTable(); dt.Load(dr2); ddl.DataValueField = "COLUMN_NAME"; ddl.DataTextField = "COLUMN_NAME"; ddl.DataSource = dt; ddl.SelectedIndexChanged += new EventHandler(ddlList_SelectedIndexChanged); ddl.DataBind(); ddl.AutoPostBack = true; ddl.EnableViewState = true; //Preserves View State info on Postbacks dr2.Close(); ddl.Items.Add("IGNORE"); dropDowns[counter] = ddl; } return dropDowns; } protected void ddlList_SelectedIndexChanged(object sender, EventArgs e) { DropDownList ddl = (DropDownList)sender; string ID = ddl.ID; } // Add TextBoxes Control to Placeholder private DropDownList[] RecreateDropDownLists() { DropDownList[] dropDowns = new DropDownList[NumberOfControls]; for (int counter = 0; counter < NumberOfControls; counter++) { DropDownList ddl = new DropDownList(); SqlDataReader dr2 = ADONET_methods.DisplayTableColumns(targettable); ddl.ID = "DropDownListID" + counter.ToString(); int NumControls = targettable.Length; DataTable dt = new DataTable(); dt.Load(dr2); ddl.DataValueField = "COLUMN_NAME"; ddl.DataTextField = "COLUMN_NAME"; ddl.DataSource = dt; ddl.SelectedIndexChanged += new EventHandler(ddlList_SelectedIndexChanged); ddl.DataBind(); ddl.AutoPostBack = true; ddl.EnableViewState = false; //Preserves View State info on Postbacks dr2.Close(); ddl.Items.Add("IGNORE"); dropDowns[counter] = ddl; } return dropDowns; } private void CreateLabels() { for (int counter = 0; counter < NumberOfControls; counter++) { Label lbl = new Label(); lbl.ID = "Label" + counter.ToString(); lbl.Text = headers[counter]; lbl.Style["position"] = "absolute"; lbl.Style["top"] = 60 * counter + 10 + "px"; lbl.Style["left"] = 250 + "px"; pnlDisplayData.Controls.Add(lbl); pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>")); } } // Add TextBoxes Control to Placeholder private void RecreateLabels() { for (int counter = 0; counter < NumberOfControls; counter++) { Label lbl = new Label(); lbl.ID = "Label" + counter.ToString(); lbl.Text = headers[counter]; lbl.Style["position"] = "absolute"; lbl.Style["top"] = 60 * counter + 10 + "px"; lbl.Style["left"] = 250 + "px"; pnlDisplayData.Controls.Add(lbl); pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>")); } } // Create TextBoxes and DropDownList data here on postback. protected override void CreateChildControls() { // create the child controls if the server control does not contains child controls this.EnsureChildControls(); // Creates a new ControlCollection. this.CreateControlCollection(); // Here we are recreating controls to persist the ViewState on every post back if (Page.IsPostBack) { RecreateDisplayPanel(); RecreateLabels(); } // Create these conrols when asp.net page is created else { PopulateFileInputTable(); CreateDisplayPanel(); CreateLabels(); } // Prevent dropdownlists and labels from being created again. if (restart == false) { this.ChildControlsCreated = true; } else if (restart == true) { this.ChildControlsCreated = false; } } private void AppendRecords() { switch (targettable) { case "ContactType": for (int r = 0; r < myInputFile.Rows.Count; r++) { resultLabel.Text = ADONET_methods.AppendDataCT(myInputFile.Rows[r], ddl_ht); } break; case "Contact": for (int r = 0; r < myInputFile.Rows.Count; r++) { resultLabel.Text = ADONET_methods.AppendDataC(myInputFile.Rows[r], ddl_ht); } break; case "AddressType": for (int r = 0; r < myInputFile.Rows.Count; r++) { resultLabel.Text = ADONET_methods.AppendDataAT(myInputFile.Rows[r], ddl_ht); } break; default: resultLabel.Text = "You do not have access to modify this table. Please select a different target table and try again."; restart = true; break; //throw new ArgumentOutOfRangeException("targettable type", targettable); } } // Read all the data from TextBoxes and DropDownLists protected void btnSubmit_Click(object sender, System.EventArgs e) { //int cnt = FindOccurence("DropDownListID"); AppendRecords(); pnlDisplayData.Visible = false; btnSubmit.Visible = false; resultLabel.Attributes.Add("style", "align:center"); btnSubmit.Style.Add("top", "auto"); btnSubmit.Style.Add("left", "auto"); btnSubmit.Style.Add("position", "absolute"); int bSubmitPosition = NumberOfControls; btnSubmit.Style.Add("top", System.Convert.ToString(bSubmitPosition)+"px"); resultLabel.Visible = true; Instructions.Visible = false; if (restart == true) { CreateChildControls(); } } private int FindOccurence(string substr) { string reqstr = Request.Form.ToString(); return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion } //}

    Read the article

  • Inserting and Deleting Sub Rows in GridView

    - by Vincent Maverick Durano
    A user in the forums (http://forums.asp.net) is asking how to insert  sub rows in GridView and also add delete functionality for the inserted sub rows. In this post I'm going to demonstrate how to this in ASP.NET WebForms.  The basic idea to achieve this is we just need to insert row data in the DataSource that is being used in GridView since the GridView rows will be generated based on the DataSource data. To make it more clear then let's build up a sample application. To start fire up Visual Studio and create a WebSite or Web Application project and then add a new WebForm. In the WebForm ASPX page add this GridView markup below:   1: <asp:gridview ID="GridView1" runat="server" AutoGenerateColumns="false" onrowdatabound="GridView1_RowDataBound"> 2: <Columns> 3: <asp:BoundField DataField="RowNumber" HeaderText="Row Number" /> 4: <asp:TemplateField HeaderText="Header 1"> 5: <ItemTemplate> 6: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 7: </ItemTemplate> 8: </asp:TemplateField> 9: <asp:TemplateField HeaderText="Header 2"> 10: <ItemTemplate> 11: <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> 12: </ItemTemplate> 13: </asp:TemplateField> 14: <asp:TemplateField HeaderText="Header 3"> 15: <ItemTemplate> 16: <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> 17: </ItemTemplate> 18: </asp:TemplateField> 19: <asp:TemplateField HeaderText="Action"> 20: <ItemTemplate> 21: <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click" Text="Insert"></asp:LinkButton> 22: </ItemTemplate> 23: </asp:TemplateField> 24: </Columns> 25: </asp:gridview>   Then at the code behind source of ASPX page you can add this codes below:   1: private DataTable FillData() { 2:   3: DataTable dt = new DataTable(); 4: DataRow dr = null; 5:   6: //Create DataTable columns 7: dt.Columns.Add(new DataColumn("RowNumber", typeof(string))); 8:   9: //Create Row for each columns 10: dr = dt.NewRow(); 11: dr["RowNumber"] = 1; 12: dt.Rows.Add(dr); 13:   14: dr = dt.NewRow(); 15: dr["RowNumber"] = 2; 16: dt.Rows.Add(dr); 17:   18: dr = dt.NewRow(); 19: dr["RowNumber"] = 3; 20: dt.Rows.Add(dr); 21:   22: dr = dt.NewRow(); 23: dr["RowNumber"] = 4; 24: dt.Rows.Add(dr); 25:   26: dr = dt.NewRow(); 27: dr["RowNumber"] = 5; 28: dt.Rows.Add(dr); 29:   30: //Store the DataTable in ViewState for future reference 31: ViewState["CurrentTable"] = dt; 32:   33: return dt; 34:   35: } 36:   37: private void BindGridView(DataTable dtSource) { 38: GridView1.DataSource = dtSource; 39: GridView1.DataBind(); 40: } 41:   42: private DataRow InsertRow(DataTable dtSource, string value) { 43: DataRow dr = dtSource.NewRow(); 44: dr["RowNumber"] = value; 45: return dr; 46: } 47: //private DataRow DeleteRow(DataTable dtSource, 48:   49: protected void Page_Load(object sender, EventArgs e) { 50: if (!IsPostBack) { 51: BindGridView(FillData()); 52: } 53: } 54:   55: protected void LinkButton1_Click(object sender, EventArgs e) { 56: LinkButton lb = (LinkButton)sender; 57: GridViewRow row = (GridViewRow)lb.NamingContainer; 58: DataTable dtCurrentData = (DataTable)ViewState["CurrentTable"]; 59: if (lb.Text == "Insert") { 60: //Insert new row below the selected row 61: dtCurrentData.Rows.InsertAt(InsertRow(dtCurrentData, row.Cells[0].Text + "-sub"), row.RowIndex + 1); 62:   63: } 64: else { 65: //Delete selected sub row 66: dtCurrentData.Rows.RemoveAt(row.RowIndex); 67: } 68:   69: BindGridView(dtCurrentData); 70: ViewState["CurrentTable"] = dtCurrentData; 71: } 72:   73: protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { 74: if (e.Row.RowType == DataControlRowType.DataRow) { 75: if (e.Row.Cells[0].Text.Contains("-sub")) { 76: ((LinkButton)e.Row.FindControl("LinkButton1")).Text = "Delete"; 77: } 78: } 79: }   As you can see the code above is pretty straight forward and self explainatory but just to give you a short explaination the code above is composed of three (3) private methods which are the FillData(), BindGridView and InsertRow(). The FillData() method is a method that returns a DataTable and basically creates a dummy data in the DataTable to be used as the GridView DataSource. You can replace the code in that method if you want to use actual data from database but for the purpose of this example I just fill the DataTable with a dummy data on it. The BindGridVew is a method that handles the actual binding of GridVew. The InsertRow() is a method that returns a DataRow. This method handles the insertion of the sub row. Now in the LinkButton OnClick event, we casted the sender to a LinkButton to determine the specific object that fires up the event and get the row values. We then reference the Data from ViewState to get the current data that is being used in the GridView. If the LinkButton text is "Insert" then we will insert new row to the DataSource ( in this case the DataTable) based on the rowIndex if not then Delete the sub row that was added. Here are some screen shots of the output below: On initial load:   After inserting a sub row:   That's it! I hope someone find this post useful!   Technorati Tags: ASP.NET,C#,GridView

    Read the article

  • Custom page sizes in paging dropdown in Telerik RadGrid

    Working with Telerik RadControls for ASP.NET AJAX is actually quite easy and the initial effort to get started with the control suite is very low. Meaning that you can easily get good result with little time. But there are usually cases where you have to go a little further and dig a little bit deeper than the standard scenarios. In this article I am going to describe how you can customize the default values (10, 20 and 50) of the drop-down list in the paging element of RadGrid. Get control over the displayed page sizes while using numeric paging... The default page sizes are good but not always good enough The paging feature in RadGrid offers you 3, well actually 4, possible page sizes in the drop-down element out-of-the box, which are 10, 20 or 50 items. You can get a fourth option by specifying a value different than the three standards for the PageSize attribute, ie. 35 or 100. The drawback in that case is that it is the initial page size. Certainly, the available choices could be more flexible or even a little bit more intelligent. For example, by taking the total count of records into consideration. There are some interesting scenarios that would justify a customized page size element: A low number of records, like 14 or similar shouldn't provide a page size of 50, A high total count of records (ie: 300+) should offer more choices, ie: 100, 200, 500, or display of all records regardless of number of records I am sure that you might have your own requirements, and I hope that the following source code snippets might be helpful. Wiring the ItemCreated event In order to adjust and manipulate the existing RadComboBox in the paging element we have to handle the OnItemCreated event of RadGrid. Simply specify your code behind method in the attribute of the RadGrid tag, like so: <telerik:RadGrid ID="RadGridLive" runat="server" AllowPaging="true" PageSize="20"    AllowSorting="true" AutoGenerateColumns="false" OnNeedDataSource="RadGridLive_NeedDataSource"    OnItemDataBound="RadGrid_ItemDataBound" OnItemCreated="RadGrid_ItemCreated">    <ClientSettings EnableRowHoverStyle="true">        <ClientEvents OnRowCreated="RowCreated" OnRowSelected="RowSelected" />        <Resizing AllowColumnResize="True" AllowRowResize="false" ResizeGridOnColumnResize="false"            ClipCellContentOnResize="true" EnableRealTimeResize="false" AllowResizeToFit="true" />        <Scrolling AllowScroll="true" ScrollHeight="360px" UseStaticHeaders="true" SaveScrollPosition="true" />        <Selecting AllowRowSelect="true" />    </ClientSettings>    <MasterTableView DataKeyNames="AdvertID">        <PagerStyle AlwaysVisible="true" Mode="NextPrevAndNumeric" />        <Columns>            <telerik:GridBoundColumn HeaderText="Listing ID" DataField="AdvertID" DataType="System.Int32"                SortExpression="AdvertID" UniqueName="AdvertID">                <HeaderStyle Width="66px" />            </telerik:GridBoundColumn>             <!--//  ... and some more columns ... -->         </Columns>    </MasterTableView></telerik:RadGrid> To provide a consistent experience for your visitors it might be helpful to display the page size selection always. This is done by setting the AlwaysVisible attribute of the PagerStyle element to true, like highlighted above. Customize the values of page size Your delegate method for the ItemCreated event should look like this: protected void RadGrid_ItemCreated(object sender, GridItemEventArgs e){    if (e.Item is GridPagerItem)    {        var dropDown = (RadComboBox)e.Item.FindControl("PageSizeComboBox");        var totalCount = ((GridPagerItem)e.Item).Paging.DataSourceCount;        var sizes = new Dictionary<string, string>() {            {"10", "10"},            {"20", "20"},            {"50", "50"}        };        if (totalCount > 100)        {            sizes.Add("100", "100");        }        if (totalCount > 200)        {            sizes.Add("200", "200");        }        sizes.Add("All", totalCount.ToString());        dropDown.Items.Clear();        foreach (var size in sizes)        {            var cboItem = new RadComboBoxItem() { Text = size.Key, Value = size.Value };            cboItem.Attributes.Add("ownerTableViewId", e.Item.OwnerTableView.ClientID);            dropDown.Items.Add(cboItem);        }        dropDown.FindItemByValue(e.Item.OwnerTableView.PageSize.ToString()).Selected = true;    }} It is important that we explicitly check the event arguments for GridPagerItem as it is the control that contains the PageSizeComboBox control that we want to manipulate. To keep the actual modification and exposure of possible page size values flexible I am filling a Dictionary with the requested 'key/value'-pairs based on the number of total records displayed in the grid. As a final step, ensure that the previously selected value is the active one using the FindItemByValue() method. Of course, there might be different requirements but I hope that the snippet above provide a first insight into customized page size value in Telerik's Grid. The Grid demos describe a more advanced approach to customize the Pager.

    Read the article

  • FileUpload and UpdatePanel: ScriptManager.RegisterPostBackControl works the second time.

    - by VansFannel
    Hello. I'm developing an ASP.NET application with C# and Visual Studio 2008 SP1. I'm using WebForms. I have an ASPX page with two UpdatePanels, one on the left that holds a TreeView and other on the right where I load dynamically user controls. One user control, that I used on right panel, has a FileUpload control and a button to save that file on server. The ascx code to save control is: <asp:UpdatePanel ID="UpdatePanelBotons" runat="server" RenderMode="Inline" UpdateMode="Conditional"> <ContentTemplate> <asp:Button ID="Save" runat="server" Text="Guardar" onclick="Save_Click" CssClass="button" /> </ContentTemplate> <Triggers> <asp:PostBackTrigger ControlID="Save" /> </Triggers> </asp:UpdatePanel> I make a full postback to upload the file to the server and save it to database. But I always getting False on FileUpload.HasFile. I problem is the right UpdatePanel. I need it to load dynamically the user controls. This panel has three UpdatePanels to load the three user controls that I use. Maybe I can use an Async File Uploader or delete the right Update Panel and do a full postback to load controls dynamically. Any advice? UPDATE: RegisterPostBackControl works... the second time I click on save button. First time FileUpload.HasFile is FALSE, and second time is TRUE. Second Update On first click I also check ScriptManager.IsInAsyncPostBack and is FALSE. I don't understand ANYTHING!! Why? The code to load user control first time, and on each postback is: DynamicControls.CreateDestination ud = this.LoadControl(ucUrl) as DynamicControls.CreateDestination; if (ud != null) { Button save = ud.FindControl("Save") as Button; if (save != null) ScriptManager1.RegisterPostBackControl(save); PanelDestination.Controls.Add(ud); } Thank you.

    Read the article

  • how to display image in repeater after AJAX AsyncFileUpload ?

    - by Gordon Shamway
    Hello i am using the AsyncFileUpload from the ajaxtoolkit, upter the upload is complete , i want to display all the images that were uploaded (and their URL is inserted into the DB) with my repeater and binding method. but its not working! the images are uploaded, the DB insert works file, but i cant see the images after the repeater is dinded. (i have to mention that if i go step by step, i do see that the ITEMBOUND is being binded and executed) <ajax:TabContainer runat="server" ID="testTab"> <ajax:TabPanel runat="server" ID="testTabContainer"> <ContentTemplate> <ajax:AsyncFileUpload ID="uploadAsyncImage" runat="server" OnUploadedComplete="InsertToTemp" ThrobberID="Throbber"/> <asp:Label ID="Throbber" runat="server" Style="display: none"> <img src="Images/indicator.gif" align="absmiddle" alt="loading" /> </asp:Label> <br /> <asp:UpdatePanel runat="server" ID="pnlImages" UpdateMode="Conditional" ChildrenAsTriggers="true"> <ContentTemplate> <asp:Repeater runat="server" ID="rptImages" > <ItemTemplate> <a href="<%# DataBinder.Eval(Container.DataItem, "PicURL")%>" rel="lightbox"> <asp:Image ImageUrl='<%# DataBinder.Eval(Container.DataItem, "PicURL")%>' Width="50" Height="50" runat="server" ID="testPic" /> </a> </ItemTemplate> </asp:Repeater> </ContentTemplate> </asp:UpdatePanel> </ContentTemplate> </ajax:TabPanel> </ajax:TabContainer> </form> also adding my Code Behind, since it might be important or will help you get an idea of what i am trying to do.private void BindRepater() { ProjDataContext db = DbContext.DbContextProvider(); var pic = from p in db.TempProdCats where p.SessionID == Session.SessionID.ToString() select new { PicURL = p.PicURL }; rptImages.DataSource = pic; rptImages.DataBind(); pnlImages.Update(); } protected void rptImages_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { Image lblCat = (Image)e.Item.FindControl("testPic"); lblCat.ImageUrl = (string)DataBinder.Eval(e.Item.DataItem, "PicURL"); pnlImages.Update(); } } your help will be highly appreciated , if any of you got any idea how to make it work...

    Read the article

  • How to eliminate one of my extra DropDownLists in C#?

    - by salvationishere
    I'm developing a C#/SQL web app in VS 2008 but for some reason I have one extra DropDownList. The very first dropdownlist displaying is empty. Can you help me identify the cause of this behavior? I'm baffled! An excerpt of my code is below. private DropDownList[] newcol; // Add DropDownList Control to Placeholder private DropDownList[] CreateDropDownLists() { DropDownList[] dropDowns = new DropDownList[NumberOfControls]; for (int counter = 0; counter < NumberOfControls; counter++) { DropDownList ddl = new DropDownList(); SqlDataReader dr2 = ADONET_methods.DisplayTableColumns(targettable); ddl.ID = "DropDownListID" + counter.ToString(); int NumControls = targettable.Length; DataTable dt = new DataTable(); dt.Load(dr2); ddl.DataValueField = "COLUMN_NAME"; ddl.DataTextField = "COLUMN_NAME"; ddl.DataSource = dt; ddl.SelectedIndexChanged += new EventHandler(ddlList_SelectedIndexChanged); ddl.DataBind(); ddl.AutoPostBack = true; ddl.EnableViewState = true; //Preserves View State info on Postbacks //ddlList.Style["position"] = "absolute"; //ddl.Style["top"] = 80 + "px"; //ddl.Style["left"] = 0 + "px"; dr2.Close(); dropDowns[counter] = ddl; } return dropDowns; } protected void ddlList_SelectedIndexChanged(object sender, EventArgs e) { DropDownList ddl = (DropDownList)sender; string ID = ddl.ID; } //Create display panel private void CreateDisplayPanel() { btnSubmit.Style.Add("top", "auto"); btnSubmit.Style.Add("left", "auto"); btnSubmit.Style.Add("position", "absolute"); newcol = CreateDropDownLists(); for (int counter = 0; counter < NumberOfControls; counter++) { pnlDisplayData.Controls.Add(newcol[counter]); pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>")); pnlDisplayData.Visible = true; pnlDisplayData.FindControl(newcol[counter].ID); } }

    Read the article

  • DropDownList not updating value

    - by annelie
    Hello, I posted a question earlier but have another problem after making those changes. The previous thread can be found here: http://stackoverflow.com/questions/2700028/binding-a-dropdownlist-inside-a-detailsview Basically, I've got a dropdownlist that's dynamically populated with a list of regions. It selects the correct region when viewing the dropdown, but when I try to edit it changes the value to null. I think it might be because it doesn't know which field to update. Previously, when the dropdown list was hardcoded, I had SelectedValue='<%# Bind("region_id")%' set on the dropdown list, and when I updated it worked fine. However, I had to move the setting of the selected value into the code behind and now it just gets set to null every time I update. Here's the aspx code: <asp:DetailsView id="DetailsView1" runat="server" AutoGenerateRows="false" DataSourceID="myMySqlDataSrc" DataKeyNames="id" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" AutoGenerateInsertButton="False" OnDataBound="DetailsView1_DataBound" > <Fields> <snip> <asp:TemplateField HeaderText="Region"> <ItemTemplate><%# Eval("region_name") %></ItemTemplate> <EditItemTemplate> <asp:DropDownList ID="RegionDropdownList" runat="server"> </asp:DropDownList> </EditItemTemplate> </asp:TemplateField> </Fields> </asp:DetailsView> And here's the code behind: protected void DetailsView1_DataBound(object sender, EventArgs e) { ArrayList regionsList = BPBusiness.getRegions(); if (DetailsView1.CurrentMode == DetailsViewMode.Edit) { DropDownList ddlRegions = (DropDownList)DetailsView1.FindControl("RegionDropdownList"); if (ddlRegions != null) { ddlRegions.DataSource = regionsList; ddlRegions.DataValueField = "Value"; ddlRegions.DataTextField = "Text"; ddlRegions.DataBind(); if (ddlRegions.Items.Contains(ddlRegions.Items.FindByValue(objBusiness.iRegionID.ToString()))) { ddlRegions.SelectedIndex = ddlRegions.Items.IndexOf(ddlRegions.Items.FindByValue(objBusiness.iRegionID.ToString())); } } } } EDIT: The database is MySql, and the update statement looks like this: myMySqlDataSrc.UpdateCommand = "UPDATE myTable SET business_name = ?, addr_line_1 = ?, addr_line_2 = ?, addr_line_3 = ?, postcode = ?, county = ?, town_city = ?, tl_url = ?, customer_id = ?, region_id = ?, description = ?, approval_status = ?, tl_user_name = ?, phone = ?, uploaders_own = ? WHERE id = ?"; Thanks, Annelie

    Read the article

  • Design time error - multiple controls with the same Id

    - by ilivewithian
    I'm using VS 2008, I have a very simple page that has a bunch of uniquely named controls. When I try to view it in design mode I get the following error: Error Rendering Control - Label12 An unhanded exception has occurred. Multiple controls with the same ID 'Label1' were found. FindControl requires that controls have unique IDs I've checked the HTML and the designer file and I can only see one control called Label1. What might be causing this? Also, here is the aspx markup I'm having trouble with? <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="CoachingAppearanceReport.aspx.vb" Inherits="AcademyPro.CoachingAppearanceReport" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <div id="appearanceDetail" class="Left CriteriaContainer"> <asp:Label ID="Label1" runat="server" Text="Appearance Type" AssociatedControlID="ddlAppearanceType" /> <asp:DropDownList ID="ddlAppearanceType" runat="server" CssClass="AppType" OnDataBound="ddlAppearanceType_DataBound" DataSourceID="odsAppearanceType" DataTextField="AppearanceType" DataValueField="AppearanceTypeCode"> </asp:DropDownList> <asp:RequiredFieldValidator ID="rfvAppearanceType" runat="server" ControlToValidate="ddlAppearanceType" InitialValue="" Text="*" ErrorMessage="The appearance type must be selected" /> <asp:Label ID="lblAppearanceType" runat="server" /> <br /> <div class="SubSettings"> <asp:Label ID="Label12" runat="server" Text="Subbed for" AssociatedControlID="ddlSubbedFor" /> <asp:DropDownList ID="ddlSubbedFor" runat="server" OnDataBound="ddlSubbedFor_DataBound" DataSourceID="odsPlayersInAgeGroup" DataTextField="PlayerName" DataValueField="PlayerID"> </asp:DropDownList> <asp:Label ID="lblSubbedFor" runat="server" /> <br /> <asp:Label ID="Label13" runat="server" Text="Mins" AssociatedControlID="txtSubMins" /> <asp:TextBox ID="txtSubMins" runat="server" MaxLength="3" CssClass="TinyWidth" /> <asp:Label ID="lblSubMins" runat="server" /> </div> </div> </ContentTemplate> </asp:UpdatePanel> </form> </body> </html>

    Read the article

  • Can i store a Queue in viewstate? only will store the first item i add to queue

    - by Mausimo
    Hey, as the question states i am trying to store a Queue in a viewstate (to track postbacks and refreshes to stop a form from resubmitting). Here is just the viewstate code: private Queue<string> p_tempQue { set { ViewState["sTemp"] = value; } get { return (Queue<string>)ViewState["sTemp"]; } } //BasePage constructor public BasePage() { //create a Queue of string //sTemp = new Queue(); this.Load += new EventHandler(this.Page_Load); this.Init += new EventHandler(this.Page_Init); } //In the 'page_Init' event we have created a simple hidden field by name 'hdnGuid' which is attached to the page on the first hit itself. protected void Page_Init(object sender, EventArgs e) { //initializing the hidden field //create a hidden field with a ID HiddenField hdnGuid = new HiddenField(); hdnGuid.ID = "hdnGuid"; //if it is the first time the page is loaded, create a new guid and assign it as the hidden field value if (!Page.IsPostBack) hdnGuid.Value = Guid.NewGuid().ToString(); //add the hidden field to the page Page.Form.Controls.Add(hdnGuid); } //In the 'page_Load' event we check if the hidden field value is same as the old value. In case the value is not same that means it's a 'postback' //and if the value is same then its 'refresh'. As per situation we set the 'httpContent.Items["Refresh"]' value. protected void Page_Load(object sender, EventArgs e) { if(p_tempQue != null) sTemp = p_tempQue; else sTemp = new Queue<string>(); //The hdnGuid will be set the first time page is loaded, else the hdnGuid //will be set after each time the form is submitted using javascript. //assign the hidden field currently on the page for manipulation HiddenField h1 = (HiddenField)(Page.Form.FindControl("hdnGuid")); //create an instance of the GuidClass GuidClass currentGuid = new GuidClass(); //set the GuidClass Guid property to the value of the hidden field currentGuid.Guid = h1.Value; //check to see if the Queue of strings contains the string which is the current Guid property of the GuidClass //if the are equal, then the page was refreshed if (sTemp.Contains<string>(currentGuid.Guid)) { //adds item as key/value pair to share data between an System.Web.IHttpModule interface and an System.Web.IHttpHandler interface during an HTTP request. System.Web.HttpContext.Current.Items.Add("IsRefresh", true); } //if they are not requal, the page is not refreshed else { //if the current Guid property in the GuidClass is not null or not an empty string //add the new Guid to the Queue if (!(currentGuid.Guid.Equals(null) || currentGuid.Guid.Equals(""))) sTemp.Enqueue(currentGuid.Guid); System.Web.HttpContext.Current.Items.Add("IsRefresh", false); } p_tempQue = sTemp; }

    Read the article

  • How to use a LinkButton inside gridview to delete selected username in the code-behind file?

    - by jenifer
    I have a "UserDetail" table in my "JobPost.mdf". I have a "Gridview1" showing the column from "UserDetail" table,which has a primary key "UserName". This "UserName" is originally saved using Membership class function. Now I add a "Delete" linkbutton to the GridView1. This "Delete" is not autogenerate button,I dragged inside the column itemtemplate from ToolBox. The GridView1's columns now become "Delete_LinkButton"+"UserName"(within the UserDetail table)+"City"(within the UserDetail table)+"IsAdmin"(within the UserDetail table) What I need is that by clicking this "delete_linkButton",it will ONLY delete the entire User Entity on the same row (link by the corresponding "UserName") from the "UserDetail" table,as well as delete all information from the AspNetDB.mdf (User,Membership,UserInRole,etc). I would like to fireup a user confirm,but not mandatory. At least I am trying to make it functional in the correct way. for example: Command UserName City IsAdmin delete ken Los Angles TRUE delete jim Toronto FALSE When I click "delete" on the first row, I need all the record about "ken" inside the "UserDetail" table to be removed. Meanwhile, all the record about "ken" in the AspNetDB.mdf will be gone, including UserinRole table. I am new to asp.net, so I don't know how to pass the commandargument of the "Delete_LinkButton" to the code-behind file LinkButton1_Click(object sender, EventArgs e), because I need one extra parameter "UserName". My partial code is listed below: <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="Delete_LinkButton" runat="server" onclick="LinkButton1_Click1" CommandArgument='<%# Eval("UserName","{0}") %>'>LinkButton</asp:LinkButton> </ItemTemplate> </asp:TemplateField> protected void Delete_LinkButton_Click(object sender, EventArgs e) { ((LinkButton) GridView1.FindControl("Delete_LinkButton")).Attributes.Add("onclick", "'return confirm('Are you sure you want to delete {0} '" + UserName); Membership.DeleteUser(UserName); JobPostDataContext db = new JobPostDataContext(); var query = from u in db.UserDetails where u.UserName == UserName select u; for (var Item in query) { db.UserDetails.DeleteOnSubmit(Item); } db.SubmitChanges(); } Please do help! Thanks in advance.

    Read the article

  • invalid postback event instead of dropdown to datagrid

    - by rima
    I faced with funny situation. I created a page which is having some value, I set these value and control my post back event also. The problem is happening when I change a component index(ex reselect a combobox which is not inside my datagrid) then I dont know why without my page call the Page_Load it goes to create a new row in grid function and all of my parameter are null! I am just receiving null exception. So in other word I try to explain the situation: when I load my page I am initializing some parameter. then everything is working fine. in my page when I change selected item of my combo box, page suppose to go and run function related to that combo box, and call page_load, but it is not going there and it goes to rowcreated function. I am trying to illustrate part of my page. Please help me because I am not receiving any error except null exception and it triger wrong even which seems so complicated for me. public partial class W_CM_FRM_02 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack && !loginFail) return; InitializeItems(); } } private void InitializeItems() { cols = new string[] { "v_classification_code", "v_classification_name" }; arrlstCMMM_CLASSIFICATION = (ArrayList)db.Select(cols, "CMMM_CLASSIFICATION", "v_classification_code <> 'N'", " ORDER BY v_classification_name"); } } protected void DGV_RFA_DETAILS_RowCreated(object sender, GridViewRowEventArgs e) { //db = (Database)Session["oCon"]; foreach (DataRow dr in arrlstCMMM_CLASSIFICATION) ((DropDownList)DGV_RFA_DETAILS.Rows[index].Cells[4].FindControl("OV_RFA_CLASSIFICATION")).Items.Add(new ListItem(dr["v_classification_name"].ToString(), dr["v_classification_code"].ToString())); } protected void V_CUSTOMER_SelectedIndexChanged(object sender, EventArgs e) { if (V_CUSTOMER.SelectedValue == "xxx" || V_CUSTOMER.SelectedValue == "ddd") V_IMPACTED_FUNCTIONS.Enabled = true; } } my form: <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="W_CM_FRM_02.aspx.cs" Inherits="W_CM_FRM_02" Title="W_CM_FRM_02" enableeventvalidation="false" EnableViewState="true"%> <td>Project name*</td> <td><asp:DropDownList ID="V_CUSTOMER" runat="server" AutoPostBack="True" onselectedindexchanged="V_CUSTOMER_SelectedIndexChanged" /></td> <td colspan = "8"> <asp:GridView ID="DGV_RFA_DETAILS" runat="server" ShowFooter="True" AutoGenerateColumns="False" CellPadding="1" ForeColor="#333333" GridLines="None" OnRowDeleting="grvRFADetails_RowDeleting" Width="100%" Style="text-align: left" onrowcreated="DGV_RFA_DETAILS_RowCreated"> <RowStyle BackColor="#FFFBD6" ForeColor="#333333" /> <Columns> <asp:BoundField DataField="ON_RowNumber" HeaderText="SNo" /> <asp:TemplateField HeaderText="RFA/RAD/Ticket No*"> <ItemTemplate> <asp:TextBox ID="OV_RFA_NO" runat="server" Width="120"></asp:TextBox> </ItemTemplate> </asp:TemplateField>

    Read the article

  • how to update only the updated rows in gridview?

    - by user603007
    what is the handiest way to update only the updated rows (only the checkbox column) in this gridview? what is a handy way to check wether the row was updated? c# public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { List<customer> listCustomer = new List<customer>(); customer cust1 = new customer(){name="fred",email="[email protected]",jobless="true"}; customer cust2 = new customer(){name="mark",email="[email protected]",jobless="false"}; listCustomer.Add(cust1); listCustomer.Add(cust2); GridView1.DataSource=listCustomer; GridView1.DataBind(); } } protected void btnUpdate_Click1(object sender, EventArgs e) { foreach (GridViewRow rw in GridView1.Rows) { CheckBox thiscontrol = (CheckBox)rw.Cells[0].FindControl("cb"); var ch = thiscontrol.Checked; //only update the updated rows? } } public class customer { public string name { get; set; } public string email { get; set; } public string jobless { get; set; } } html <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="gridviewUpdate._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:CheckBox ID="jobless" runat="server" Checked='<%# Eval("jobless").ToString().Equals("true") %>' /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="email" /> <asp:BoundField DataField="name" /> </Columns> </asp:GridView> </div>

    Read the article

  • How to eliminate one of my extra DropDownLists in ASP.NET?

    - by salvationishere
    I'm developing a C#/SQL web app in VS 2008 but for some reason I have one extra DropDownList. The very first dropdownlist displaying is empty. Can you help me identify the cause of this behavior? I'm baffled! An excerpt of my code is below. private DropDownList[] newcol; // Add DropDownList Control to Placeholder private DropDownList[] CreateDropDownLists() { DropDownList[] dropDowns = new DropDownList[NumberOfControls]; for (int counter = 0; counter < NumberOfControls; counter++) { DropDownList ddl = new DropDownList(); SqlDataReader dr2 = ADONET_methods.DisplayTableColumns(targettable); ddl.ID = "DropDownListID" + counter.ToString(); int NumControls = targettable.Length; DataTable dt = new DataTable(); dt.Load(dr2); ddl.DataValueField = "COLUMN_NAME"; ddl.DataTextField = "COLUMN_NAME"; ddl.DataSource = dt; ddl.SelectedIndexChanged += new EventHandler(ddlList_SelectedIndexChanged); ddl.DataBind(); ddl.AutoPostBack = true; ddl.EnableViewState = true; //Preserves View State info on Postbacks //ddlList.Style["position"] = "absolute"; //ddl.Style["top"] = 80 + "px"; //ddl.Style["left"] = 0 + "px"; dr2.Close(); dropDowns[counter] = ddl; } return dropDowns; } protected void ddlList_SelectedIndexChanged(object sender, EventArgs e) { DropDownList ddl = (DropDownList)sender; string ID = ddl.ID; } //Create display panel private void CreateDisplayPanel() { btnSubmit.Style.Add("top", "auto"); btnSubmit.Style.Add("left", "auto"); btnSubmit.Style.Add("position", "absolute"); newcol = CreateDropDownLists(); for (int counter = 0; counter < NumberOfControls; counter++) { pnlDisplayData.Controls.Add(newcol[counter]); pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>")); pnlDisplayData.Visible = true; pnlDisplayData.FindControl(newcol[counter].ID); } }

    Read the article

  • Accesing server control from withing app_code class

    - by OverSeven
    My question is about how to acces a server control (listbox) that is located in default.aspx. I wish to acces this control in Functions.cs (this class is located in the App_Code folder). My page structures: - 1 masterpage with 1 content holder - Default.aspx (all the controls are within the content place holder) - Functions.cs (located in App_Code) Now when i try to fill up the listbox elements i get the error "object reference not set to an instance of an object." What i have tried to gain acces to this control: (this code is located in Functions.cs in App_Code). This is basicly showing some items in the listbox that are located in the xml file private static string file = HttpContext.Current.Server.MapPath("~/App_Data/Questions.xml"); public static void ListItems() { XmlDocument XMLDoc = new XmlDocument(); XMLDoc.Load(file); XPathNavigator nav = XMLDoc.CreateNavigator(); XPathExpression expr; expr = nav.Compile("/root/file/naam"); XPathNodeIterator iterator = nav.Select(expr); //ATTEMPT to get acces to ServerControl(listbox) Page page = (Page)HttpContext.Current.Handler; ListBox test = (ListBox)page.FindControl("lbTest"); //control is called lbTest in Default.aspx test.Items.Clear(); while (iterator.MoveNext()) { test.Items.Add(iterator.Current.Value); } } Code from the default.apx file <%@ Page Title="" Language="C#" MasterPageFile="~/MasterFile.master" AutoEventWireup="true" CodeFile="default.aspx.cs" Inherits="default" Debug="true" %> <%@ MasterType TypeName="Master" %> <asp:Content ID="Content1" ContentPlaceHolderID="cphContent" Runat="Server" > <asp:MultiView ID="mvTest" runat="server" > <asp:View ID="vCollection" runat="server"> <asp:ListBox ID="lbTest" runat="server" CssClass="listbox" ></asp:ListBox> </asp:View> </asp:MultiView> </asp:Content> The masterfile itself just has 1 placeholder. Then i call upon the funcion ListItems in the Default.aspx.cs file protected void Page_Load(object sender, EventArgs e) { Functions.ListItems(); } Regards.

    Read the article

  • How to configure a GridView CommandField to trigger Full Page Update in UpdatePanel

    - by Frinavale
    I have 2 user controls on my page. One is used for searching, and the other is used for editing (along with a few other things). The user control that provides the search functionality uses a GridView to display the search results. This GridView has a CommandField used for editing (showEditButton="true"). I would like to place the GridView into an UpdatePanel so that paging through the search results will be smooth. The thing is that when the user clicks the Edit Link (the CommandField) I need to preform a full page postback so that the search user control can be hidden and the edit user control can be displayed. Edit: the reason I need to do a full page postback is because the edit user control is outside of the UpdatePanel that my GridView is in. It is not only outside the UpdatePanel, but it's in a completely different user control. I have no idea how to add the CommandField as a full page postback trigger to the UpdatePanel. The PostBackTrigger (which is used to indicate the controls cause a full page postback) takes a ControlID as a parameter; however the CommandButton does not have an ID...and you can see why I'm having a problem with this. Update on what else I've tried to solve the problem: I took a new approach to solving the problem. In my new approach, I used a TemplateField instead of a CommandField. I placed a LinkButton control in the TemplateField and gave it a name. During the GridView's RowDataBound event I retrieved the LinkButton control and added it to the UpdatePanel's Triggers. This is the ASP Markup for the UpdatePanel and the GridView <asp:UpdatePanel ID="SearchResultsUpdateSection" runat="server"> <ContentTemplate> <asp:GridView ID="SearchResultsGrid" runat="server" AllowPaging="true" AutoGenerateColumns="false"> <Columns> <asp:TemplateField> <HeaderTemplate></HeaderTemplate> <ItemTemplate> <asp:LinkButton ID="Edit" runat="server" Text="Edit"></asp:LinkButton> </ItemTemplate> </asp:TemplateField> <asp:BoundField ...... </Columns> </asp:GridView> </ContentTemplate> </asp:UpdatePanel> In my VB.NET code. I implemented a function that handles the GridView's RowDataBound event. In this method I find the LinkButton for the row being bound to, create a PostBackTrigger for the LinkButton, and add it to the UpdatePanel's Triggers. This means that a PostBackTrigger is created for every "edit" LinkButton in the GridView Edit: this did not create a PostBackTrigger for Every "edit" LinkButton because the ID is the same for all LinkButtons in the GridView. Private Sub SearchResultsGrid_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles SearchResultsGrod.RowDataBound If e.Row.RowType = DataControlRowType.Header Then ''I am doing stuff here that does not pertain to the problem Else Dim editLink As LinkButton = CType(e.Row.FindControl("Edit"), LinkButton) If editLink IsNot Nothing Then Dim fullPageTrigger As New PostBackTrigger fullPageTrigger.ControlID = editLink.ID SearchResultsUpdateSection.Triggers.Add(fullPageTrigger) End If End If End Sub And instead of handling the GridView's RowEditing event for editing purposes i use the RowCommand instead. Private Sub SearchResultsGrid_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles SearchResultsGrid.RowCommand RaiseEvent EditRecord(Me, New EventArgs()) End Sub This new approach didn't work at all because all of the LinkButtons in the GridView have the same ID. After reading the MSDN article on the UpdatePanel.Triggers Property I have the impression that Triggers can only be defined declaratively. This would mean that anything I did in the VB code wouldn't work. Any advise would be greatly appreciated. Thanks, -Frinny

    Read the article

< Previous Page | 5 6 7 8 9 10  | Next Page >