Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set DataSource on controls within asp.net UserControl?

I have created my first asp.net UserControl that I will use in several places throughout my app. It contains a FormView to display fields of the record in a DataTable.

It all seems fine, except, I can't figure out how to set the DataSource on the FormView that is within the UserControl. I want to set the DataSource in a method in code-behind.

I see from intellisense that the UserControl does not have a DataSource property, but it does have a DataBind method. I can imagine that one might need to set different DataSources on multiple controls within a UserControl, so there must be some method for drilling into a UserControl, but I cannot figure it out.

Here is the aspx code:

<%@ Register src="Controls/JobDetail.ascx" tagname="JobDetail" tagprefix="uc1" %>

 ...
 <uc1:JobDetail ID="UserControlJobDetail" runat="server" />
 ...

Here is the method that attempts to set the DataSource:

public void BindJobRecord(string SelectedJobNo)
{
    UserControlJobDetail.DataSource = LMDataClass.GetJob(SelectedJobNo);
    UserControlJobDetail.DataBind();
}

And here is the UserControl:

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

<asp:FormView ID="fvJobDetail" runat="server" DataKeyNames="job_num">
  <ItemTemplate>
   <div style="float: left; border-width: 1px;" class="LabelStyle TextBoxStyle" >
    <table>
      <tr>
       <td><asp:label runat="server" ID="lblJobNo" Text='Job No' /></td>
       <td><asp:TextBox runat="server" ID="txtJobNo" Text='<%# Eval("job_num") %>' /></td>
      </tr>
      <tr>
       <td><asp:label runat="server" ID="Label2" Text='Customer' /></td>
       <td><asp:TextBox runat="server" ID="txtCustNo" Text='<%# Eval("cust_num") %>' /></td>
      </tr>
      <tr>
        <td><asp:label runat="server" ID="Label3" Text='Quote No' /></td>
        <td><asp:TextBox runat="server" ID="txtQuoteNo" Text='<%# DataBinder.Eval(Container.DataItem, "quote_no", "{0:00000;;.}") %>' /></td>
       </tr>
       <tr>
        <td><asp:label runat="server" ID="Label4" Text='Po No.' /></td>
        <td><asp:TextBox runat="server" ID="TextBox4" Text='<%# Eval("p_o_num") %>' /></td>
       </tr>
    </table>        
    </div>
</ItemTemplate>               
</asp:FormView>
like image 558
MattSlay Avatar asked Apr 15 '09 17:04

MattSlay


1 Answers

Create a property DataSource on user control like below:

public object DataSource
{
  get
  {
    return this.fvJobDetail.DataSource;
  }
  set
  {
    this.fvJobDetail.DataSource = value;
  }
}

Do the same for the DataBind() method.

like image 56
Albert Avatar answered Nov 13 '22 08:11

Albert