Databind custom user control

I've built a user control for a gallery implementation (galleryImage - made up of a textbox, image and some other controls). galleryImage sits inside a repeater. I get the correct number of instances of the galleryImage and I am able to databind the title field from the database to each instance. The problem comes up when I change the title inside the user control as my database entry is not updating (using LINQ).

I know that I am missing something...

Here are the applicable bits of my code:

ASCX.CS File:

public partial class controls_galleryImage : System.Web.UI.UserControl
{
private string _titleText = "";

protected void Page_Load(object sender, EventArgs e)
{

}
    protected void Page_PreRender(object sender, EventArgs e)
{
TextBox1.Text = myImageTitle;

    [Bindable(true)]
public string myImageTitle
{
get
{
return _titleText;
}
set
{
_titleText = value;
}
}

public void Button2_Click(object sender, EventArgs e)
{
myImageTitle = TextBox1.Text;
Page.DataBind();
}
}
ASCX File:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="galleryImage.ascx.cs" Inherits="controls_galleryImage" %>
.
.
.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" Text="Update" onclick="Button2_Click" />
<asp:Button ID="Button3" runat="server" Text="Cancel" />
ASPX File:
<%@ Register src="controls/galleryImage.ascx" TagName="GalleryImage" TagPrefix="asp" %>
.
.
.
.
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="ImageDataSource">
<ItemTemplate>
<asp:GalleryImage ID="GalleryImage1" runat="server" myImageTitle="<%# Bind('imageTitle') %> "></asp:GalleryImage>
</ItemTemplate>
</asp:Repeater>
.
.
.
<asp:LinqDataSource ID="ImageDataSource" runat="server"
ContextTypeName="DataClassesDataContext" EnableUpdate="True"
TableName="tblGalleryImages">
</asp:LinqDataSource>
 
0
sule93
4/26/2009 10:12:13 PM
asp.net.custom-server-controls 3498 articles. 0 followers. Follow

3 Replies
745 Views

Similar Articles

[PageSpeed] 16

Hi,

When using Repeater we need to manually update the record. But there's no code logic in your code that handles this. I'd like to show how to write a User Control in this case. Here I use GridView for the simplicity. If you need a Repeater sample please feel free to let me know.

ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication2.WebUserControl1" %>

<asp:TextBox BackColor="Red" ID="TextBox1" runat="server"></asp:TextBox>

You can either use the "Update" LinkButton in the left column or this button to update

<asp:Button ID="Button1" runat="server" Text="Update" CommandName="Update" />

 

ascx.cs:

public partial class WebUserControl1 : System.Web.UI.UserControl

{

public string CompanyName

{

get

{

return this.TextBox1.Text;

}

set

{

this.TextBox1.Text = value;

}

}

protected void Page_Load(object sender, EventArgs e)

{

}

}

 

 

aspx:

<asp:GridView AutoGenerateColumns="false" DataKeyNames="CustomerID" AutoGenerateEditButton="true" DataSourceID="LinqDataSource1" ID="GridView1" runat="server">

<Columns>

<asp:TemplateField>

<ItemTemplate>

<%#Eval("CompanyName") %></ItemTemplate>

<EditItemTemplate>

<uc1:WebUserControl1 ID="WebUserControl11" runat="server" CompanyName='<%#Bind("CompanyName") %>' />

</EditItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

 

<asp:LinqDataSource ID="LinqDataSource1" runat="server"

ContextTypeName="WebApplication2.DataClasses1DataContext" EnableUpdate="True"

TableName="Customers">

</asp:LinqDataSource>


Sincerely,
Allen Chen
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
0
Allen
4/28/2009 6:01:00 AM

 Thanks for the reply. This approach worked.

 If you have some time, would you mind pointing me to a Repeater example?

0
sule93
4/29/2009 11:47:34 AM

Hi,

Repeater sample:

ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication5.WebUserControl1" %>

<asp:TextBox BackColor="Red" ID="TextBox1" runat="server"></asp:TextBox>

You can either use the "Update" LinkButton in the left column or this button to update

<asp:Button ID="Button1" runat="server" Text="Update" CommandName="Update" />

 

ascx.cs:

public partial class WebUserControl1 : System.Web.UI.UserControl

{

public string CompanyName

{

get

{

return this.TextBox1.Text;

}

set

{

this.TextBox1.Text = value;

}

}

protected void Page_Load(object sender, EventArgs e)

{

 

}

 

}

aspx.cs:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Collections.Specialized;

namespace WebApplication5

{

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

 

}

protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)

{

if (ViewState["editindex"] != null)

{

int editindex = Convert.ToInt32(ViewState["editindex"]);

Repeater1.Controls[editindex].FindControl(

"ReadOnlyPanel").Visible = true;

Repeater1.Controls[editindex].FindControl(

"EditPanel").Visible = false;

}

Control c = (Control)e.CommandSource;

switch (e.CommandName) {

case "Edit": {

c.FindControl("ReadOnlyPanel").Visible = false;

c.FindControl("EditPanel").Visible = true;

ViewState["editindex"] = e.CommandArgument;

break;

}

case "Update":

{

RepeaterItem item = TryFindRepeaterItem(c);

WebUserControl1 wuc = (WebUserControl1)item.FindControl("WebUserControl11");

Label lblkey = (Label)item.FindControl("key");

Label lblold = (Label)item.FindControl("oldvalue");

string key = lblkey.Text;

string value=wuc.CompanyName;

string oldvalue=lblold.Text;

ListDictionary keydic = new ListDictionary();

keydic.Add("CustomerID",key);

ListDictionary valuedic=new ListDictionary();

valuedic.Add("CompanyName", value);

ListDictionary oldvaluedic=new ListDictionary();

oldvaluedic.Add("CompanyName",oldvalue); this.LinqDataSource1.Update(keydic, valuedic,oldvaluedic);

this.Repeater1.DataBind();

ViewState["editindex"] = null;

break;

}

}

 

}

RepeaterItem TryFindRepeaterItem(Control c) {

if (c == null) { return null; }

if (c is RepeaterItem) { return c as RepeaterItem; }

else {

return TryFindRepeaterItem(c.NamingContainer);

}

}

}

}

aspx: <asp:Repeater DataSourceID="LinqDataSource1" ID="Repeater1" runat="server"

onitemcommand="Repeater1_ItemCommand">

<ItemTemplate>

<asp:Panel ID="ReadOnlyPanel" runat="server">

<asp:LinkButton CommandName="Edit" CommandArgument='<%#((RepeaterItem)Container).ItemIndex %>' ID="LinkButton1" runat="server">Edit</asp:LinkButton>

<%#Eval("CompanyName") %>

</asp:Panel>

 

<asp:Panel Visible="false" ID="EditPanel" runat="server">

<asp:LinkButton CommandName="Update" ID="LinkButton2" runat="server">Update</asp:LinkButton>

<asp:LinkButton CommandName="Cancel" ID="LinkButton3" runat="server">Cancel</asp:LinkButton>

<asp:Label Visible="false" ID="key" runat="server" Text='<%#Eval("CustomerID") %>'></asp:Label>

<asp:Label Visible="false" ID="oldvalue" runat="server" Text='<%#Eval("CompanyName") %>'></asp:Label>

<uc1:WebUserControl1 ID="WebUserControl11" runat="server" CompanyName='<%#Eval("CompanyName") %>' />

</asp:Panel>

</ItemTemplate>

</asp:Repeater>

<asp:LinqDataSource ID="LinqDataSource1" runat="server"

ContextTypeName="WebApplication5.DataClasses1DataContext" EnableUpdate="True"

TableName="Customers">

</asp:LinqDataSource>


Sincerely,
Allen Chen
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
0
Allen
4/30/2009 2:13:35 AM
Reply:

Similar Artilces:

Usercontrol vs Custom Server Controls, Any need for Custom Server Controls
Hello I'm new to ASP.Net so this is probably a stupid question but, is there any need to create customer server controls now that you can pre-compile usercontrols into a dll and thus easily share between applications? This blog post from David Ebb describes how to do it and the restrictions he note don't seem that bad (other than being able to embed resources such as images in the dll). http://blogs.msdn.com/davidebb/archive/2005/10/30/487160.aspx His article desribes the techniques for ASP.Net 2.0 and he suggests that there will be further improvements in .Net 3.5 in this ar...

Custom Server Control Made of Custom Controls?
I'm giving myself a crash course in custom server controls, and I have a quick general question. Can I have a custom server control that is composed of other server controls I created. I'm pretty sure the answer is yes, but I want to be positive. Yes http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpcondevelopingcompositecontrols.asp Shows how to combine existing controls into a new control using class composition. -ron Thanks! ASP.NET so rocks! Making page components extensible objects is such a great idea! I love it....

problems listenening to events on a custom server control from another custom server control
 Hi all,I am having problems listening to events on one of custom server controls(AddBookmark) from another custom server control(BookmarkList). The listener or the BookmarkList control has a property that can be set to the AddBookmark control (string at design but the reference is obtained at run-time). I am able to get a reference to the AddBookmark control and add a listener to it on the BookmarkList control on the OnPrender of BookmarkList. But the problem is that when the events on AddBookmark gets fired, the listener added from the BookmarkList is no longer present and the listene...

Custom Server Control Vs Web Parts, Any need for Custom Server Control
Hello I've just posted a similar question on why you need server controls when you can pre-compile usercontrols and redistribute them. http://forums.asp.net/p/1397433/3010100.aspx#3010100 I've seen lots of (usercontrol vs web part) but not much on web part vs custom server control. According to the MSDN site you can put web parts onto a normal asp.net page outside of a web part zone and they behave just like custom server controls. So, if you are creating a bunch of controls for redistribution to customer asp.net sites and/or SharePoint sites why don't you just create Web Par...

Custom User Controls v. Custom Web Controls
Hi! Is it better for me to begin coding my controls instead of just designing them? What would the benefits be? I meen, i seem to be able to get all i need from just putting stuff together on an ASCX file but i'm obviously missing a huge concept here... please explain! Hi, creating user controls is indeed easier than creating custom server controls because you can simply drag & drop other controls on the form, easily add events to it, ... Custom controls however are better when you want to reuse them in several other projects. I like to create custom controls for small, reusable com...

load user control from server custom control
hi all,i have a 3rd party menu control that consists of a bunch of HyperLinks and a PlaceHolder control (C# v1.1.4) . links to .ascx files are retrieved from a data source, and when the page containing the control is loaded or a link clicked, the control uses this.Page.LoadControl(strLink) to add the .ascx to the PlaceHolder. fine and dandy, probably wouldnt have done it that way myself, but i'm stuck with it :)the problem is events: i can't raise 'em :( if i have for example a Button control on one of the .ascx pages, the Button.Click will go by unnoticed on the post-back. stran...

Using a user control in a custom server control.
I've created a custom server control and am trying to add a user control to the rendering of the server control.  Is this possible?  If so, hints as to how this is done would be GREATLY appreciated!  Thanks in advance for considering an answer to this question. Wendi Use the LoadControl method. For example:   Controls.Add(LoadControl("~/controls/login.ascx"))Steven BeyRecursion: see Recursion My server control renders a table with x number of rows.  I want to add a user control to each row of the table, last column.  I do not know how ...

how to have both server controls and html controls rendered in a custom control?
I have a custom control in which there is an html text box.when you click on it , a div containing a table is appeared and according to what you select in that table a text is set to the text box. It works fine but the problem is: as the text box is an html element it doesn't have viewstate and when a post back occures in the page its value disappeares.I tried a hidden field to keep its value.again there is another problem : I put this custom control in a usercontrol and put the usercontrol in a multiview and by clicking on a button this view is selected and by clicking another bu...

Help! Custom Server Control using User Control
I've been bashing my head for a few days on this problem. My Custom Server Control loads the User Control and renders it properly.  But, when I run the web application the controls (ex: buttons) from the User Control is not firing the event (ex: a button click to change the label's text)?Here is a snippet of part of my code:    Protected Overrides Sub CreateChildControls()        plhPanel = New System.Web.UI.WebControls.PlaceHolder        ContentFileLoaded = New System.Web.UI.U...

Server Web User Control or Web Custom Control
Ok, I made a DataGrid I like, stuck it in a Web Control Lib, and then to my toolbar. Now I want to take my nice little control and add it to a greater control, maybe place some buttons around it etc. I could always inherit from it in a new custom control and dynamically add the buttons, but I thought about using a Web User Control. I thought I could easily create a Web User Control, drop on my grid and the buttons on a form, and expose some properties and events, but once I got into it, I got a feeling that this isn't what a Web User Control is for. When designing a control li...

Custom Control within a Custom Control
I have two individual custom controls say custom cc1 and cc2. cc1 is communicating to cc2 using event delegate mechanism.I have tested the behaviour by dropping cc1 and cc2 onto a Web Page and it works fine. I want to create a third custom control say cc3 which should contain both cc1 and cc2. So that if i drag and drop cc3 onto a Web Page i can acheive exactly what i am doing above. The problem is that i am not sure how to call/register a custom control within a custom control ? Any clue ? Thanks!! Hi, Do you mean adding custom control to custom control? I think you can use the same wa...

Custom Controls or User Controls
Hi, I have to create a menu control and I am unable to decide between a custom control or user control.  Apart from the fact that a custom control can be inserted into the toolbox what are the other advantages and disadvantages of each like performance, and so on.  Plus how do I decide between the two. Thanks Arjuna. Hello Please refer to the KB article Overview of user controls vs. custom controls Hope it helps, JessicaJessica CaoSincerely,Microsoft Online Community Support“Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer...

user control or custom control ?
i have datagrid which shows monthyear user control for each row. The month year user control has two drop down list. one is for year and other one is for month. So for each row in particular column i'll have that user control loaded. it works fine but ut takes lot of time in rendering when there are 200 rows. what would be the solution. will custom control help? Hi,Lax4u: Some tips i am not quite sure. First, you can disable the viewstate of the userControl to make it not load so many information in each postback and store the necessary in the global range. Second, Caching porting of th...

user control and custom control
What is different between Web User Control and Web Custom Control? http://support.microsoft.com/kb/893667Thanks, EdMicrosoft MVP - ASP/ASP.NET I would suggest you to google the word "different between Web User Control and Web Custom Control" to get more informations and results...Regards,Vinz"Code, Beer and Music" that's my way of being a programmer!How to get your Forum Question Answered | Blog | CodeASP.NET Web custom controls are compiled components that run on the server and that encapsulate user-interface and other related functionality into reusable pack...

User Control VB.Net x Web Custom Control
I was thinking in create a user control in VB.Net, and use it in a Asp.Net as possible? So I thought about it is gonna be better than make a Web Custom Control, so i thought again, nope... But i need to know better because a don't have a progress bar in asp.net for example.... Could Somebody tell me about??? in a reallity i know the asnwer but i would like to explain by myself... Thank's Antonio...

Web resources about - Databind custom user control - asp.net.custom-server-controls

TAG Heuer: Luxury watches for men and women since 1860
Find the TAG Heuer store closest to your home: TAG Heuer, a much referenced brand in luxury watches and other prestige products - chronographs, ...

dotnet HighCharts inside UpdatePanel
Read my article about the HighCharts.net databind? A frequently question regards the possibility to get functioning a dotnet.HighCharts chart ...

Jackson Data Binding Message Serialization
... languages we’re immediately concerned with, and more or less straightforward. For my Java-based server I am using Jackson and Jackson-databind ...

Boost ASP.NET performance with deferred content loading
A comprehensive example of how to improve the perceived speed of your pages, by implementing user controls to encapsulate secondary content and ...

Maven Repository: Open Source
Categories - Popular - Contact Us Artifacts/Year Popular Categories Aspect Oriented Actor Frameworks Application Metrics Build Tools Bytecode ...

RSSBus ADO.NET Provider for Google - Overview
The Google Data Provider gives developers the power to easily connect .NET applications to popular Google Services including GMail, Google Docs, ...

CodeSOD: Today's Article is Brought to You by the Letters "WTF"
... = "Z" dr.Item("Alphabets") = "Z" tempTable.Rows.Add(dr) End Select Next Me.rptAlphabets.DataSource = tempTable Me.rptAlphabets.DataBind() End ...

HOW TO: Use SQLite in C# Metro style app
The web site and blog of Tim Heuer, Program Manager for Microsoft XAML. A resource to learn how to develop software with XAML technologies. This ...

SQLite WinRT wrapper for Windows Phone
... named cities.db (in the app’s local folder) and then adding the contents of the Cities table to an ObservableCollection . You can then databind ...

Listbox, Why Art Thou Blanking?
... the user moves downwards we balance the buffers by transferring the excess buffer from the top buffer (red) to the bottom buffer and re-databind ...

Resources last updated: 12/24/2015 8:24:04 PM