Search Results

Search found 493 results on 20 pages for 'databind'.

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

  • Use DataSource in DataFormWebPart

    - by Bryan Shen
    I'm writing a custom web part that extends DataFormWebPart. public class MyCustomWebPart : DataFormWebPart{ // other methods public override void DataBind() { XmlDataSource source = new XmlDataSource() { Data = @" <Person> <name cap='true'>Bryan</name> <occupation>student</occupation> </Person> " }; DataSources.Add(source); base.DataBind(); } } The only noticeable thing I do is overriding the DataBind() method, where I use xml as the data source. After I deploy the web part, I set the following XSL to it: <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:template match="/"> <xmp> <xsl:copy-of select="*"/> </xmp> </xsl:template> </xsl:stylesheet> This xsl will surround the input xml with a tag . So I expected the web part to display the original xml data as I wrote in C# code behind. But what shows up in the web part is this: <Person> <name cap="true" /> <occupation /> </Person> All the values within the inner-most tags disappear. What's going on? Can anybody help me? Thanks.

    Read the article

  • How to Use DataSource Property in DataFormWebPart

    - by Bryan Shen
    I'm writing a custom web part that extends DataFormWebPart. public class MyCustomWebPart : DataFormWebPart{ // other methods public override void DataBind() { XmlDataSource source = new XmlDataSource() { Data = @" <Person> <name cap='true'>Bryan</name> <occupation>student</occupation> </Person> " }; DataSources.Add(source); base.DataBind(); } } The only noticeable thing I do is overriding the DataBind() method, where I use xml as the data source. After I deploy the web part, I set the following XSL to it: <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:template match="/"> <xmp> <xsl:copy-of select="*"/> </xmp> </xsl:template> </xsl:stylesheet> This xsl will surround the input xml with a tag . So I expected the web part to display the original xml data as I wrote in C# code behind. But what shows up in the web part is this: <Person> <name cap="true" /> <occupation /> </Person> All the values within the inner-most tags disappear. What's going on? Can anybody help me? Thanks.

    Read the article

  • Asp.Net Random Error

    - by John Boker
    At random times, twice in the past two weeks, the we application will start to error and not work until I recycle the app pool in IIS. The specific error and stacktrace are: System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.InvalidCastException: Unable to cast object of type 'System.Guid' to type 'System.String'. at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression) at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source) at DigitalScout.WEDS.Business.Slug.GetTeamPath(String teamID) at DigitalScout.WEDS.WebApp.Code.Navigator.TeamNavigator.Home(String teamID) at ASP.management_default_aspx.__DataBind__control7(Object sender, EventArgs e) at System.Web.UI.Control.OnDataBinding(EventArgs e) at System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) at System.Web.UI.Control.DataBindChildren() at System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) at System.Web.UI.WebControls.Repeater.CreateControlHierarchy(Boolean useDataSource) at System.Web.UI.WebControls.Repeater.OnDataBinding(EventArgs e) at System.Web.UI.Control.DataBindChildren() at System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) at System.Web.UI.WebControls.Repeater.CreateControlHierarchy(Boolean useDataSource) at System.Web.UI.WebControls.Repeater.OnDataBinding(EventArgs e) at DigitalScout.WEDS.WebApp.Management._default.Page_Load(Object sender, EventArgs e) at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at DigitalScout.WEDS.WebApp.Code.BaseClass.Pages.ManagementPage.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) --- End of inner exception stack trace --- at System.Web.UI.Page.HandleError(Exception e) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.management_default_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) This error happens for every user of the system until the app pool is recycled. Any help on this would be helpful as we are not able to reproduce the error.

    Read the article

  • sorting filtered data in asp.net listview

    - by user791345
    I've created a listview that's filled up with a list of guitars from the database on page load like so: protected void Page_Load(object sender, EventArgs e) { SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["GuitarsLTDBConnectionString"].ToString()); SqlCommand cmd = new SqlCommand("SELECT * FROM Guitars", con); SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText, con); DataTable dt = new DataTable(); da.Fill(dt); lvGuitars.DataSource = dt; lvGuitars.DataBind(); } The following code filters that list of guitars by a certain Make when the user checks the checkbox corresponding to that make protected void chkOrgs_SelectedIndexChanged(object sender, EventArgs e) { DataTable dt = (DataTable)lvGuitars.DataSource; DataView dv = new DataView(dt); if (chkOrgs.SelectedValue == "Gibson") { dv.RowFilter = "Make = 'Gibson' OR Make='Fender'"; } lvGuitars.DataSource = dv.ToTable(); lvGuitars.DataBind(); } Now, what I want to do is be able to sort the latest data that is present within the listview. Meaning, if sort is clicked before filtering, the it should sort all data. If sort is clicked after filtering, it should sort the filtered data. I'm using the following code, which is triggered upon a LinkButton click protected void lnkSortResults_Click(object sender, EventArgs e) { DataTable dt = (DataTable)lvGuitars.DataSource; DataView dv = new DataView(dt); dv.Sort = "Make ASC"; lvGuitars.DataSource = dv.ToTable(); lvGuitars.DataBind(); } The problem is that all the data that the listview was loaded with before any filtering is sorted, and not the latest filtered data. How can I change this code so that the latest data available in the listview is the one that's sorted? Thanks

    Read the article

  • ASP.NET:Paging when deleting rows

    - by Niels Bosma
    I have a datagrid where a row can be deleted (using ajax). I'm have problem with the pager in the following scenario: Lets say my PageSize is 10, I have 101 rows so that's 11 pages with the last page with an single element. Let no assume that I'm on page 10 (PageIndex=9) and delete a row. Then I go to the 11'th page (who's now empty and doesn't really exist). ASP now shows me the EmptyDataTemplate and no pager so I can't go back. My approach (which isn't working) is to detect this scenario and step one page back: public void Bind() { gridMain.DataBind(); } public void SetPage(int page) { gridMain.PageIndex = page; gridMain.DataBind(); } protected void ldsGridMain_Selecting(object sender, LinqDataSourceSelectEventArgs e) { selectArgs = e; e.Result = (new EnquiryListController()).GetEnquiryList(OnBind(this), supplier); } protected void ldsGridMain_Selected(object sender, LinqDataSourceStatusEventArgs e) { totalRows = selectArgs.Arguments.TotalRowCount; //Detect if we need to update the page: if (gridMain.PageIndex > 0 && (gridMain.PageSize * gridMain.PageIndex + 1) > totalRows) SetPage(gridMain.PageIndex - 1); } protected void gridMain_PageIndexChanging(object sender, GridViewPageEventArgs e) { SetPage(e.NewPageIndex); } I can see that SetPage is called with the the right page index, but the databind doesn't seem to called as I still get the EmptyDataTemplate.

    Read the article

  • C# ASP.NET Binding Controls via Generic Method

    - by OverTech
    I have a few web applications that I maintain and I find myself very often writing the same block of code over and over again to bind a GridView to a data source. I'm trying to create a Generic method to handle data binding but I'm having trouble getting it to work with Repeaters and DataLists. Here is the Generic method I have so far: public void BindControl<T>(T control, SqlCommand sql) where T : System.Web.UI.WebControls.BaseDataBoundControl { cmd = sql; cn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { control.DataSource = dr; control.DataBind(); } dr.Close(); cn.Close(); } That way I can just define my CommandText then make a call to "BindControls(myGridView, cmd)" instead of retyping this same basic block of code every time I need to bind a grid. The problem is, this doesn't work with Repeaters or DataLists. Each of these controls inherit their respective "DataSource" and "DataBind" methods from different classes. Someone on another forum suggested that I implement an interface, but I'm not sure how to make that work either. The GridView, Datalist and Repeater get their respective "DataBind" methods from BaseDataBoundControl, BaseDataList, and Repeater classes. How would I go about creating a single interface to tie them all together? Or am I better off just using 3 overloads for this method? Dave

    Read the article

  • How can I clear viewstate of a dropdownlist inside a usercontrol? Should I?

    - by tbilly
    I have a web user control with a dropdownlist inside of it. When the usercontrol's databind event is called, it automatically fires the dropdownlists databind event. In the dropdownlist's ondatabound event handler an 'other' option is appended to the end of the dropdownlist. The usercontrol is loaded multiple times, depending on selection of other controls on the page. When the page loads initially, there are no items in the usercontrol except the 'other' option. Then when I call the user control's databind event the control reloads, with 4 items plus the 'other' option. The text for the first item in the list is the 'other' option's text, not what it should be. I've stepped through the databound event of the dropdownlist and have found that all items are loading correctly. It appears that the dropdownlist's viewstate is the culprit, that the dropdownlist's original item[1] text is overwriting the new text. I've tried disabling viewstate on the dropdownlist, but then it wouldn't load at all. Should I try to clear the dropdownlist's viewstate? How do I do that? Any suggestions would be greatly appreciated.

    Read the article

  • Help with interesting VS2010 and SQL2008 bug

    - by user355770
    Hey So im using Visual Studio 2010 to create a webpage. im calling some tabels from sql server 2008 here is where im confused... The code runs fine no errors. The pages works except im missing my rows in my 3rd column from the table. Everything else shows up. Ive checked to make sure the names are matching everywhere and that in sql the joins and such worked. Its just very weird that i'd be missing my 2 rows from the 3rd column. anyone have any ideas to help?? the error is in the tab called research material else if (tabTagId == "tpArlington_ProjectInformation") { repArlington_ProjectInformation.DataSource = ds; repArlington_ProjectInformation.DataBind(); } else if (tabTagId == "tpArlington_Plan") { repArlington_Plan.DataSource = ds; repArlington_Plan.DataBind(); } else if (tabTagId == "tpArlington_ResearchMaterial") { repArlington_ResearchMaterial.DataSource = ds; repArlington_ResearchMaterial.DataBind(); } else if (Session["projectAbbreviation"].ToString() == "ARLING") { tpArlington_ProjectInformation.HeaderText = "Project Information"; tpArlington_ProjectInformation.Visible = true; tpArlington_Plan.HeaderText = "Plan"; tpArlington_Plan.Visible = true; tpArlington_ResearchMaterial.HeaderText = "ResearchMaterial"; tpArlington_ResearchMaterial.Visible = true; getTabData("tpArlington_ProjectInformation"); getTabData("tpArlington_Plan"); getTabData("tpArlington_ReasearchMaterial"); } the 2 other tabs work perfect. the research material is where the problem is. the stuff in the tab doesn't come up. the text in the tab DOES come up but not the stuff from sql. the stuff in sql looks good, the ids match and everything is joined properly otherwise the other 2 tabs wouldnt work. that is what is confusing me. any suggestions or specific info you need just ask. thanks!

    Read the article

  • Dropdown list bound to object data source - how to update on a button click

    - by Jen
    This is probably something really stupidly simple.. I have a drop down list bound to an object data source. I have set AppendDataBoundItems to true so that I can have an initial select. <asp:DropDownList ID="Accommodations1" runat="server" AutoPostBack="true" DataTextField="AccommodationTypeDescription" DataValueField="Id" OnDataBound="Accommodations1_DataBound" onSelectedIndexChanged="Accommodations1_SelectedIndexChanged" Width="200px" DataSourceID="AccommodationDs" AppendDataBoundItems="true"> <asp:ListItem Text="Select" Value=""></asp:ListItem> </asp:DropDownList> <asp:ObjectDataSource ID="AccommodationDs" runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="ListByPropertyId" TypeName="PropertyAccommodationController"> <SelectParameters> <asp:Parameter Name="PropertyId" Type="Int32" /> </SelectParameters> </asp:ObjectDataSource> I have a button which adds an accommodaton - so after that happens I need the dropdown list to update to include the new accommodation. So I've tried calling databind on the dropdownlist, and databind on the datasource - and nothing is making this dropdown list update. eg. PropertyAccommodations1.DataBind(); Could someone please let me know what I'm doing wrong. Originally I thought it was due to an update panel issue.. but I've removed the update panel and it still doesn't work (and checked the master page doesn't include an update panel). Thanks!!

    Read the article

  • Page_load event firing twice. User control not properly loading

    - by Phil
    Here is the code I am using to pull my usercontrol (content.ascx): Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'load module If TheModule = "content" Then Dim control As UserControl = LoadControl("~\Modules\Content.ascx") Controls.Add(control) End If End Sub Within the usercontrol is the following code (data access taken care of by DAAB and ive replaced sql statements with 'sql'): Imports System.Data.SqlClient Imports System.Data Imports System.Web.Configuration Imports Microsoft.Practices.EnterpriseLibrary.Common Imports Microsoft.Practices.EnterpriseLibrary.Data Partial Class Modules_WebUserControl Inherits System.Web.UI.UserControl Dim db As Database = DatabaseFactory.CreateDatabase() Dim command As SqlCommand 'database Dim reader As IDataReader 'general vars Dim pageid As Integer Dim did As Integer Dim contentid As Integer Dim dotpos As String Dim ext As String Dim content As String Dim folder As String Dim downloadstring As String Function getimage(ByVal strin As String) As String If strin > "" Then dotpos = InStrRev(strin, ".") ext = Right(strin, Len(strin) - dotpos) getimage = ext & ".gif" Else getimage = String.Empty End If Return getimage End Function Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load, Me.Load 'test Response.Write("(1 Test from within page_load)") 'get session vars folder = Session("folder") pageid = Session("pageid") did = Session("did") 'main content command = db.GetSqlStringCommand("sql") db.AddInParameter(command, "@pageid", DbType.Int32, pageid) reader = db.ExecuteReader(command) While reader.Read If reader("content") IsNot DBNull.Value Then content = Replace(reader("content"), Chr(38) + Chr(97) + Chr(109) + Chr(112) + Chr(59) + Chr(98) + Chr(104) + Chr(99) + Chr(112) + Chr(61) + Chr(49), "") If reader("id") IsNot DBNull.Value Then contentid = reader("id") End If Else contentid = -1 content = String.Empty End If End While Outputcontent.Text = content 'contacts info If did = 0 Then command = db.GetSqlStringCommand("sql") db.AddInParameter(command, "@contentid", DbType.Int32, contentid) reader = db.ExecuteReader(command) While reader.Read() Contactinforepeater.DataSource = reader Contactinforepeater.DataBind() End While End If If Not did = 0 Then command = (db.GetSqlStringCommand("sql") db.AddInParameter(command, "@contentid", DbType.Int32, contentid) db.AddInParameter(command, "@did", DbType.Int32, did) reader = db.ExecuteReader(command) While reader.Read Contactinforepeater.DataSource = reader Contactinforepeater.DataBind() End While End If 'downloads box command = db.GetSqlStringCommand("sql") db.AddInParameter(command, "@contentid", DbType.Int32, contentid) reader = db.ExecuteReader(command) While reader.Read If reader("filename") IsNot DBNull.Value Then downloadstring += "<a href='/documents/" & folder & "/" & reader("filename") & "'>" downloadstring += "<img src=images/" & getimage(reader("filename")) & " border=0 align=absmiddle />" End If If reader("filesize") IsNot DBNull.Value Then downloadstring += Convert.ToInt32((reader("filesize") / 1000)) & "kb - " End If If reader("filename") IsNot DBNull.Value Then downloadstring += "<a href='/documents/" & Session("folder") & "/" & reader("filename") & "'>" & reader("description") & "</a><br />" End If End While Dim downloadsarray As ArrayList downloadsarray = New ArrayList If downloadstring IsNot Nothing Then downloadsarray.Add(downloadstring) End If If downloadsarray.Count > 0 Then DownloadsRepeater.DataSource = downloadsarray DownloadsRepeater.DataBind() End If 'get links command = db.GetSqlStringCommand("sql") db.AddInParameter(command, "@contentid", DbType.Int32, contentid) reader = db.ExecuteReader(command) While reader.Read Linksrepeater.DataSource = reader Linksrepeater.DataBind() End While End Sub End Class Now instead of seeing my page content and what should be within the repeaters on the page all I get is 2 x the output of Response.Write("(1 Test from within page_load)") (1 Test from within page_load)(1 Test from within page_load) This leads me to believe the page_load is firing twice, but not properly displaying all the information. Please can one of you willing experts help me to get this working? Thanks a lot in advance

    Read the article

  • How to Edit data in nested Listview

    - by miti737
    I am using listview to display a list of items and a nested listview to show list of features to each item. Both parent and child listview need to able Insert,Edit and delete operation. It works fine for parent listview. But when I try to edit an child item, The edit button does not take it into Edit mode. Can you please suggest me what I am missing in my code? <asp:ListView ID="lvParent" runat="server" OnItemDataBound="lvParent_ItemDataBound" onitemcanceling="lvParent_ItemCanceling" onitemcommand="lvParent_ItemCommand" DataKeyNames="ItemID" onitemdeleting="lvParent_ItemDeleting" oniteminserting="lvParent_ItemInserting" > <LayoutTemplate> <asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder> <div align="right"> <asp:Button ID="btnInsert" runat="server" Text="ADD Item" onclick="btnInsert_Click"/> </div> </LayoutTemplate> <ItemTemplate> <table runat="server" cellpadding="0" cellspacing="0" border="0" width="100%"> <tr> <td> <div id="dvDetail"> <span >Description</span> <asp:TextBox ID="txtDescription" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Description") %>' TextMode="MultiLine" ></asp:TextBox> </div> <div id="dvFeature" > <span>Feature List</span> <asp:ListView ID="lvChild" runat="server" InsertItemPosition="LastItem" DataKeyNames="FeatureID" OnItemCommand="lvChild_ItemCommand" OnItemCanceling="lvChild_ItemCanceling" OnItemDeleting="lvChild_ItemDeleting" OnItemEditing="lvChild_ItemEditing" OnItemInserting="lvChild_ItemInserting" OnItemUpdating="lvChild_ItemUpdating" DataSource='<%# DataBinder.Eval(Container.DataItem, "FeatureList") %>' > <LayoutTemplate> <ul > <asp:PlaceHolder runat="server" ID="itemPlaceHolder" ></asp:PlaceHolder> </ul> </LayoutTemplate> <ItemTemplate> <li> <span class="dvList"><%# DataBinder.Eval(Container.DataItem, "FeatureTitle")%></span> <div class="dvButton" > <asp:ImageButton ID="btnEdit" runat="server" ImageUrl="/Images/edit_16x16.gif" AlternateText= "Edit" CommandName="Edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "FeatureID") %>' Width="12" Height="12" /> <asp:ImageButton ID="btnDelete" runat="server" ImageUrl="/Images/delete_16x16.gif" AlternateText= "Delete" CommandName="Delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "FeatureID") %>' Width="12" Height="12" /> </div> </li> </ItemTemplate> <EditItemTemplate> <li> <asp:TextBox ID="txtFeature" Text='<%# DataBinder.Eval(Container.DataItem, "FeatureTitle")%>' runat="server"></asp:TextBox> <div class="dvButton"> <asp:ImageButton ID="btnUpdate" runat="server" ImageUrl="/Images/ok_16x16.gif" AlternateText= "Update" CommandName="Update" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "FeatureID") %>' Width="12" Height="12" /> <asp:ImageButton ID="btnCancel" runat="server" ImageUrl="/Images/delete_16x16.gif" AlternateText= "Cancel" CommandName="Cancel" Width="12" Height="12" CausesValidation="false" /> </div> </li> </EditItemTemplate> <InsertItemTemplate> <asp:TextBox ID="txtFeature" runat="server"></asp:TextBox> <div class="dvButton"> <asp:ImageButton ID="btnInsert" runat="server" ImageUrl="/Images/ok_16x16.gif" AlternateText= "Insert" CommandName="Insert" Width="12" Height="12" /> <asp:ImageButton ID="btnCancel" runat="server" ImageUrl="/Images/delete_16x16.gif" AlternateText= "Cancel" CommandName="Cancel" Width="12" Height="12" CausesValidation="false" /> </div> </InsertItemTemplate> </asp:ListView> </div> </td> </tr> <tr> <td align="right"> <div id="dvButton" > <asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Save" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ItemID") %>' /> <asp:Button ID="btnDelete" runat="server" Text="Delete" CssClass="Cancel" CommandName="Delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ItemID") %>' /> </div> </td> </tr> </table> </ItemTemplate> </asp:ListView> Code Behind: protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack == false) { BindData(); } } private void BindData() { MyDataContext data = new MyDataContext(); var result = from itm in data.ItemLists where itm.ItemID == iItemID select new { itm.ItemID, itm.Description, FeatureList = itm.Features }; lvParent.DataSource = result; lvParent.DataBind(); } protected void lvChild_ItemEditing(object sender, ListViewEditEventArgs e) { ListView lvChild = sender as ListView; lvChild.EditIndex = e.NewEditIndex; lvChild.DataBind(); } Edit: protected void lvChild_ItemEditing(object sender, ListViewEditEventArgs e) { ListView lvChild = sender as ListView; lvChild.EditIndex = e.NewEditIndex; lvChild.DataBind(); } If I use "lvChild.DataBind()" in 'ItemEditing' event, the total list of child items goes away if I click 'edit' protected void lvChild_ItemEditing(object sender, ListViewEditEventArgs e) { ListView lvChild = sender as ListView; lvChild.EditIndex = e.NewEditIndex; } if I get rid of 'lvChild.Databind' in ItemEditing event, it goes to Edit mode after clicking the 'edit' button twice . And though it shows textbox control of EditItemTemplate, it appears as a blank textbox (does not bind existing value to edit).

    Read the article

  • How to get distinct values from the List&lt;T&gt; with LINQ

    - by Vincent Maverick Durano
    Recently I was working with data from a generic List<T> and one of my objectives is to get the distinct values that is found in the List. Consider that we have this simple class that holds the following properties: public class Product { public string Make { get; set; } public string Model { get; set; } }   Now in the page code behind we will create a list of product by doing the following: private List<Product> GetProducts() { List<Product> products = new List<Product>(); Product p = new Product(); p.Make = "Samsung"; p.Model = "Galaxy S 1"; products.Add(p); p = new Product(); p.Make = "Samsung"; p.Model = "Galaxy S 2"; products.Add(p); p = new Product(); p.Make = "Samsung"; p.Model = "Galaxy Note"; products.Add(p); p = new Product(); p.Make = "Apple"; p.Model = "iPhone 4"; products.Add(p); p = new Product(); p.Make = "Apple"; p.Model = "iPhone 4s"; products.Add(p); p = new Product(); p.Make = "HTC"; p.Model = "Sensation"; products.Add(p); p = new Product(); p.Make = "HTC"; p.Model = "Desire"; products.Add(p); p = new Product(); p.Make = "Nokia"; p.Model = "Some Model"; products.Add(p); p = new Product(); p.Make = "Nokia"; p.Model = "Some Model"; products.Add(p); p = new Product(); p.Make = "Sony Ericsson"; p.Model = "800i"; products.Add(p); p = new Product(); p.Make = "Sony Ericsson"; p.Model = "800i"; products.Add(p); return products; }   And then let’s bind the products to the GridView. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Gridview1.DataSource = GetProducts(); Gridview1.DataBind(); } }   Running the code will display something like this in the page: Now what I want is to get the distinct row values from the list. So what I did is to use the LINQ Distinct operator and unfortunately it doesn't work. In order for it work is you must use the overload method of the Distinct operator for you to get the desired results. So I’ve added this IEqualityComparer<T> class to compare values: class ProductComparer : IEqualityComparer<Product> { public bool Equals(Product x, Product y) { if (Object.ReferenceEquals(x, y)) return true; if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) return false; return x.Make == y.Make && x.Model == y.Model; } public int GetHashCode(Product product) { if (Object.ReferenceEquals(product, null)) return 0; int hashProductName = product.Make == null ? 0 : product.Make.GetHashCode(); int hashProductCode = product.Model.GetHashCode(); return hashProductName ^ hashProductCode; } }   After that you can then bind the GridView like this: protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Gridview1.DataSource = GetProducts().Distinct(new ProductComparer()); Gridview1.DataBind(); } }   Running the page will give you the desired output below: As you notice, it now eliminates the duplicate rows in the GridView. Now what if we only want to get the distinct values for a certain field. For example I want to get the distinct “Make” values such as Samsung, Apple, HTC, Nokia and Sony Ericsson and populate them to a DropDownList control for filtering purposes. I was hoping the the Distinct operator has an overload that can compare values based on the property value like (GetProducts().Distinct(o => o.PropertyToCompare). But unfortunately it doesn’t provide that overload so what I did as a workaround is to use the GroupBy,Select and First LINQ query operators to achieve what I want. Here’s the code to get the distinct values of a certain field. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DropDownList1.DataSource = GetProducts().GroupBy(o => o.Make).Select(o => o.First()); DropDownList1.DataTextField = "Make"; DropDownList1.DataValueField = "Model"; DropDownList1.DataBind(); } } Running the code will display the following output below:   That’s it! I hope someone find this post useful!

    Read the article

  • LINQ, "Argument types do not match" error, what does it mean, how do I address it?

    - by Biff MaGriff
    Hello, I'm new to linq and I'm trying to databind to an anonymous type. I'm using SubSonic 3.0 as my DAL. I'm doing a select from 2 tables like so var myDeal = (from u in db.Users select new { UserID = u.UserID, UserRoleID = (from ur in u.UserRoles where u.UserRoleID == ur.UserRoleID select ur).FirstOrDefault().UserRoleID }); foreach (var v in myDeal) //dies first time here { } Then when I databind or try to iterate through the collection I get the "Argument types do not match" error during run time. I'm not sure what is going on here.

    Read the article

  • Want to bind querystring in postbackurl of imagebutton in gridview?

    - by Sikender
    Hi ,when i try to databind the '<%#Eval("EntryID") %>' to the ImageButton's postbackurl as <asp:ImageButton ID="ibtnEdit" runat="server" CommandName="Edit" CommandArgument='<%#DataBinder.Eval(Container.DataItem,"SystemEmailID")%>' ImageUrl="~/Images/edit-list.gif" PostBackUrl="~/Edit_SyatemEmails.aspx?blogentry=edit&id=<%#DataBinder.Eval(Container.DataItem,"SystemEmailID")%>"/> it's failed, then i updated the code to <asp:ImageButton ID="ibtnBlogEntryEdit" PostBackUrl='"~/admin/BlogEntry.aspx?blogentry=edit&entryid=" & <%# Eval("EntryID") %>' SkinID="edit" runat="server" /> well,the above code has pass the debugging,but failed to databind to the postbackurl,the result as http://localhost/dovoshow/"~/admin/BlogEntry.aspx?blogentry=edit&entryid="%20&%20<%#%20Eval("EntryID")%20%> so,anyonw know how to solve it ,help me thanks

    Read the article

  • MVP on Asp.Net WebForms

    - by Nicolas Irisarri
    I'm not clear about this.... When having a gridview on the View, is the controller who has to set up the Data source, columns, etc? or I just have to expose the DataBinding stuff, fire it from the controller and let the html/codebehind on the view handle all the rendering and wiring up? To be more precise: on the view should I have private GridView _gv public _IList<Poco> Source { get {_gv.DataSource;} set {_gv.DataSource = value; _gv.DataBind();} } Or should it be (from http://stackoverflow.com/questions/153222/mvp-pattern-passive-view-and-exposing-complex-types-through-iview-asp-net-web) private GridView _datasource; public DataSource { get { return _datasource; } set { _datasource = value; _datasource.DataBind(); } } Maybe I'm having it all wrong .... Where can I find an example that is not a "Hello world" example on MVP for ASP.Net???

    Read the article

  • sorting and paging with gridview asp.net

    - by dangerisgo
    I'm trying to get a gridview to sort and page manually with no success. The problem is that when a user clicks the column they want to sort, it sorts that page, but doesn't sort the datasource (dataview) behind the gridview. So when they progress to a different page, their sort is lost. Pretty much I'm looking for a sort that will actually sort the datasource behind the gridview. Here is what I have so far: protected void GridView_OnSort(object sender, GridViewSortEventArgs e) { String sortExpression = e.SortExpression; if (GridViewSortDirection == SortDirection.Ascending) { DataView myDataView = new DataView(mybll.GetItemsOrdered()); myDataView.Sort = sortExpression + " DESC"; GridView.DataSource = myDataView; GridView.DataBind(); } else { DataView myDataView = new DataView(mybll.GetItemsOrdered()); myDataView.Sort = sortExpression + " ASC"; GridView.DataSource = myDataView; GridView.DataBind(); } } Any help would be appreciated. Thanks.

    Read the article

  • Saving State Dynamic UserControls...Help!

    - by Cognitronic
    I have page with a LinkButton on it that when clicked, I'd like to add a Usercontrol to the page. I need to be able to add/remove as many controls as the user would like. The Usercontrol consists of three dropdownlists. The first dropdownlist has it's auotpostback property set to true and hooks up the OnSelectedIndexChanged event that when fired will load the remaining two dropdownlists with the appropriate values. My problem is that no matter where I put the code in the host page, the usercontrol is not being loaded properly. I know I have to recreate the usercontrols on every postback and I've created a method that is being executed in the hosting pages OnPreInit method. I'm still getting the following error: The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases. Here is my code: Thank you!!!! bool createAgain = false; IList<FilterOptionsCollectionView> OptionControls { get { if (SessionManager.Current["controls"] != null) return (IList<FilterOptionsCollectionView>)SessionManager.Current["controls"]; else SessionManager.Current["controls"] = new List<FilterOptionsCollectionView>(); return (IList<FilterOptionsCollectionView>)SessionManager.Current["controls"]; } set { SessionManager.Current["controls"] = value; } } protected void Page_Load(object sender, EventArgs e) { Master.Page.Title = Title; LoadViewControls(Master.MainContent, Master.SideBar, Master.ToolBarContainer); } protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); System.Web.UI.MasterPage m = Master; Control control = GetPostBackControl(this); if ((control != null && control.ClientID == (lbAddAndCondtion.ClientID) || createAgain)) { createAgain = true; CreateUserControl(control.ID); } } protected void AddAndConditionClicked(object o, EventArgs e) { var control = LoadControl("~/Views/FilterOptionsCollectionView.ascx"); OptionControls.Add((FilterOptionsCollectionView)control); control.ID = "options" + OptionControls.Count.ToString(); phConditions.Controls.Add(control); } public event EventHandler<Insight.Presenters.PageViewArg> OnLoadData; private Control FindControlRecursive(Control root, string id) { if (root.ID == id) { return root; } foreach (Control c in root.Controls) { Control t = FindControlRecursive(c, id); if (t != null) { return t; } } return null; } protected Control GetPostBackControl(System.Web.UI.Page page) { Control control = null; string ctrlname = Page.Request.Params["__EVENTTARGET"]; if (ctrlname != null && ctrlname != String.Empty) { control = FindControlRecursive(page, ctrlname.Split('$')[2]); } else { string ctrlStr = String.Empty; Control c = null; foreach (string ctl in Page.Request.Form) { if (ctl.EndsWith(".x") || ctl.EndsWith(".y")) { ctrlStr = ctl.Substring(0, ctl.Length - 2); c = page.FindControl(ctrlStr); } else { c = page.FindControl(ctl); } if (c is System.Web.UI.WebControls.CheckBox || c is System.Web.UI.WebControls.CheckBoxList) { control = c; break; } } } return control; } protected void CreateUserControl(string controlID) { try { if (createAgain && phConditions != null) { if (OptionControls.Count > 0) { phConditions.Controls.Clear(); foreach (var c in OptionControls) { phConditions.Controls.Add(c); } } } } catch (Exception ex) { throw ex; } } Here is the usercontrol's code: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="FilterOptionsCollectionView.ascx.cs" Inherits="Insight.Website.Views.FilterOptionsCollectionView" %> namespace Insight.Website.Views { [ViewStateModeById] public partial class FilterOptionsCollectionView : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } protected override void OnInit(EventArgs e) { LoadColumns(); ddlColumns.SelectedIndexChanged += new RadComboBoxSelectedIndexChangedEventHandler(ColumnsSelectedIndexChanged); base.OnInit(e); } protected void ColumnsSelectedIndexChanged(object o, EventArgs e) { LoadCriteria(); } public void LoadColumns() { ddlColumns.DataSource = User.GetItemSearchProperties(); ddlColumns.DataTextField = "SearchColumn"; ddlColumns.DataValueField = "CriteriaSearchControlType"; ddlColumns.DataBind(); LoadCriteria(); } private void LoadCriteria() { var controlType = User.GetItemSearchProperties()[ddlColumns.SelectedIndex].CriteriaSearchControlType; var ops = User.GetItemSearchProperties()[ddlColumns.SelectedIndex].ValidOperators; ddlOperators.DataSource = ops; ddlOperators.DataTextField = "key"; ddlOperators.DataValueField = "value"; ddlOperators.DataBind(); switch (controlType) { case ResourceStrings.ViewFilter_ControlTypes_DDL: criteriaDDL.Visible = true; criteriaText.Visible = false; var crit = User.GetItemSearchProperties()[ddlColumns.SelectedIndex].SearchCriteria; ddlCriteria.DataSource = crit; ddlCriteria.DataBind(); break; case ResourceStrings.ViewFilter_ControlTypes_Text: criteriaDDL.Visible = false; criteriaText.Visible = true; break; } } public event EventHandler OnColumnChanged; public ISearchCriterion FilterOptionsValues { get; set; } } }

    Read the article

  • Databinding gives "System.Data.DataRowView" instead of actual values

    - by iTayb
    This is my code: string SQL = "SELECT email FROM members WHERE subscribe=true"; string myConnString = Application["ConnectionString"].ToString(); OleDbConnection myConnection = new OleDbConnection(myConnString); OleDbCommand myCommand = new OleDbCommand(SQL, myConnection); myConnection.Open(); OleDbDataAdapter MyAdapter = new OleDbDataAdapter(myCommand); DataSet ds = new DataSet(); MyAdapter.Fill(ds); MailsListBox.DataSource = ds; MailsListBox.DataBind(); GridView1.DataSource = ds; GridView1.DataBind(); myConnection.Close(); And so it looks: As you see, the GridView shows the dataset just fine, and the ListBox fails it. What happened? How can I fix it? Thank you very much.

    Read the article

  • LLBLGenProDataSource : cannot see updates values of newly inserted item from a FormView

    - by tbone
    After performing a FormView.InsertItem, I am unable to read the new values from the bound object within the LLBLGenProDataSource that the FormView is bound to. I have tracing turned on, I can see the insert happen, and the data does make it into the database, yet when I examine the contents of LLBLGenProDataSource.EntityCollection(0) (there is only one item in the collection) I do not see the values from the FormView.....yet, they are somehow being inserted into the database. Relevant code: <llblgenpro:LLBLGenProDataSource ID="llbDataSource" runat="server" MaxNumberOfItemsToReturn="1" DataContainerType="EntityCollection" EntityCollectionTypeName="Domain.CollectionClasses.MetricCollection, Domain" LivePersistence="True" ThrowExceptionOnIllegalFieldInput="true" /> Private Sub frmEdit_ItemCreated(ByVal sender As Object, ByVal e As System.EventArgs) Handles frmEdit.ItemCreated If Me.llbDataSource.EntityCollection.Count = 0 Then Me.frmEdit.ChangeMode(FormViewMode.Insert) Me.llbDataSource.EntityCollection.Add(New MetricEntity) Me.frmEdit.DataBind() Else LoadDropdowns() End If End Sub Private Sub cmdSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSave.Click If Me.frmEdit.CurrentMode = FormViewMode.Edit Then Me.frmEdit.UpdateItem(False) ElseIf Me.frmEdit.CurrentMode = FormViewMode.Insert Then Me.frmEdit.InsertItem(False) 'Me.llbDataSource.DataBind() 'NOPE! Response.Redirect("~/MetricDetail.aspx?MetricCode=" & Me.llbDataSource.EntityCollection(0).Fields("MetricCode").CurrentValue.ToString) End If End Sub

    Read the article

  • Grid View Pagination.

    - by Wondering
    Dear All, I have a grid view and I want to implement Pagination functionality.This is working fine. protected DataSet FillDataSet() { string source = "Database=GridTest;Server=Localhost;Trusted_Connection=yes"; con = new SqlConnection(source); cmd = new SqlCommand("proc_mygrid", con); ds = new DataSet(); da = new SqlDataAdapter(cmd); da.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); return ds; } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { int newPagenumber = e.NewPageIndex; GridView1.PageIndex = newPagenumber; GridView1.DataSource = FillDataSet(); GridView1.DataBind(); } But the problem is for each pagination I have to call FillDataSet(); Is there any way to stop that.Any other coding approach? Thanks.

    Read the article

  • Updating the datalist in a RadComboBox

    - by jphenow
    So I'm just struggling with a lot of little things in the web app so I'm checking up with all kinds of stuff to make sure i'm not breaking it cause of stupid problems. At some point in my web app (trying to keep it mostly Asynchronous) I have to update the list in my RadComboBox because something was added. Do I just need to call RadComboBox.DataBind() again? Since I don't explicitly use its datasource(I do it in the manual insert using a string fashion) object to insert my new record do I need to tell that to update? The list just doesn't seem to update when i just call databind so I feel like i need to have the datasource recheck for entries or SOMETHING Thanks

    Read the article

  • jQuery.ajax success callback function not executed

    - by Frank Michael Kraft
    I have a JavaScript Ajax call (jQuery.ajax), that does not execute the success callback function. $.ajax({ url: target, contentType: 'application/json; charset=utf-8', type: 'POST', // type: 'GET', dataType: 'jsonp', error: function (xhr, status) { alert(status); }, success: function (result) { alert("Callback done!"); // grid.dataBind(result.results); // grid.dataBind(result); } }); I see in firebug, that the request is posted and the correct result in terms of the json is returned as expected. What is wrong?

    Read the article

  • ASP.NET - working with GridView Programmatically

    - by JMSA
    I am continuing from this post. After much Googling, I have come up with this code to edit cells programmatically: using System; using System.Data; using System.Configuration; using System.Collections; 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 Ice_Web_Portal.BO; namespace GridView___Test { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { GridView1.DataSource = Course.GetCourses(); GridView1.DataBind(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridViewRow row = GridView1.Rows[e.NewEditIndex]; GridView1.EditIndex = e.NewEditIndex; GridView1.DataSource = Course.GetCourses(); GridView1.DataBind(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { TextBox txtID = (TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]; TextBox txtCourseCode = (TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]; TextBox txtCourseName = (TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]; TextBox txtCourseTextBookCode = (TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]; Course item = new Course(); item.ID = Convert.ToInt32(txtID.Text); item.CourseCode = txtCourseCode.Text; item.CourseName = txtCourseName.Text; item.TextBookCode = txtCourseTextBookCode.Text; bool success = Course.Update(item); labMessage.Text = success.ToString(); GridView1.EditIndex = -1; GridView1.DataSource = Course.GetCourses(); GridView1.DataBind(); } } } But 2 problems are happening. (1) I need to press command buttons twice to Edit/Update. (2) Changes in the cell values are not updated in the database. I.e. edited cell values are not committing. Can anyone give me a solution?

    Read the article

  • asp.net - csharp - jquery - looking for a better and usage solution

    - by LostLord
    hi my dear friends i have a little problem about using jquery...(i reeally do not know jquery but i forced to use it) i am using vs 2008 - asp.net web app with c# also i am using telerik controls in my pages also i am using sqldatasources (Connecting to storedprocedures) in my pages my pages base on master and content pages and in content pages i have mutiviews ================================================================================= in one of the views(inside one of those multiviews)i had made two radcombo boxes for country and city requirement like cascading dropdowns as parent and child combo boxes. i used old way for doing that , i mean i used update panel and in the SelectedIndexChange Event of Parent RadComboBox(Country) i Wrote this code : protected void RadcomboboxCountry_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e) { hfSelectedCo_ID.Value = RadcomboboxCountry.SelectedValue; RadcomboboxCity.Items.Clear(); RadcomboboxCity.Items.Add(new RadComboBoxItem(" ...", "5")); RadcomboboxCity.DataBind(); RadcomboboxCity.SelectedIndex = 0; } my child radcombo box can fill by upper code , let me tell you how : the child sqldatasource have a sp that has a parameter and i fill that parameter by this line - hfSelectedCo_ID.Value = RadcbCoNameInInsert.SelectedValue; RadcbCoNameInInsert.SelectedValue means country ID. after doing that SelectedIndexChange Event of Parent RadComboBox(Country) could not be fire therefore i forced to set the autopostback property to true. afetr doing that every thing was ok until some one told me can u control focus and keydown of your radcombo boxes (when u press enter key on the parent combobox[country] , so child combobox gets focus -- and when u press upperkey on child radcombobox [city], so parent combobox[country] gets focus) (For Users That Do Not Want To Use Mouse for Input Info And Choose items) i told him this is web app , not win form and we can not do that. i googled it and i found jquery the only way for doing that ... so i started using jquery . i wrote this code with jquery for both of them : <script src="../JQuery/jquery-1.4.1.js" language="javascript" type="text/javascript"></script> <script type="text/javascript"> $(function() { $('input[id$=RadcomboboxCountry_Input]').focus(); $('input[id$=RadcomboboxCountry_Input]').select(); $('input[id$=RadcomboboxCountry_Input]').bind('keyup', function(e) { var code = (e.keyCode ? e.keyCode : e.which); if (code == 13) { -----------> Enter Key $('input[id$=RadcomboboxCity_Input]').focus(); $('input[id$=RadcomboboxCity_Input]').select(); } }); $('input[id$=RadcomboboxCity_Input]').bind('keyup', function(e) { var code = (e.keyCode ? e.keyCode : e.which); if (code == 38) { -----------> Upper Key $('input[id$=RadcomboboxCountry_Input]').focus(); $('input[id$=RadcomboboxCountry_Input]').select(); } }); }); </script> this jquery code worked BBBBBBUUUUUUUTTTTTT autopostback=true of the Parent RadComboBox Became A Problem , Because when SelectedIndex Change Of ParentRadComboBox is fired after that Telerik Skins runs and after that i lost parent ComboBox Focus and we should use mouse but we don't want it.... for fix this problem i decided to set autopostback of perentCB to false and convert protected void RadcomboboxCountry_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e) { hfSelectedCo_ID.Value = RadcomboboxCountry.SelectedValue; RadcomboboxCity.Items.Clear(); RadcomboboxCity.Items.Add(new RadComboBoxItem(" ...", "5")); RadcomboboxCity.DataBind(); RadcomboboxCity.SelectedIndex = 0; } to a public non static method without parameters and call it with jquey like this : (i used onclientchanged property of parentcombo box like onclientchanged = "MyMethodForParentCB_InJquery();" insread of selectedindexchange event) public void MyMethodForParentCB_InCodeBehind() { hfSelectedCo_ID.Value = RadcomboboxCountry.SelectedValue; RadcomboboxCity.Items.Clear(); RadcomboboxCity.Items.Add(new RadComboBoxItem(" ...", "5")); RadcomboboxCity.DataBind(); RadcomboboxCity.SelectedIndex = 0; } for doing that i read the blow manual and do that step by step : ======================================================================= http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=732 ======================================================================= but this manual is about static methods and this is my new problem ... when i am using static method like : public static void MyMethodForParentCB_InCodeBehind() { hfSelectedCo_ID.Value = RadcomboboxCountry.SelectedValue; RadcomboboxCity.Items.Clear(); RadcomboboxCity.Items.Add(new RadComboBoxItem(" ...", "5")); RadcomboboxCity.DataBind(); RadcomboboxCity.SelectedIndex = 0; } so i recieved some errors and this method could not recognize my controls and hidden field... one of those errors like this : Error 2 An object reference is required for the non-static field, method, or property 'Darman.SuperAdmin.Users.hfSelectedCo_ID' C:\Javad\Copy of Darman 6\Darman\SuperAdmin\Users.aspx.cs 231 13 Darman any idea or is there any way to call non static methods with jquery (i know we can not do that but is there another way to solve my problem)???????????????

    Read the article

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