简体   繁体   中英

ASP.net user control with DataSource

My user control has several components, but the main is a CheckBoxList, I want to load it with a SqlDataSource, from the page, allowing me to use multiple instances of my control with different sources.

My first attempt was to expose the checkboxlist's DataSourceID in my user control:

public String DataSourceID
{
   get { return myCheckList.DataSourceID; }
   set { myCheckList.DataSourceID = value; }
}

And set it from my aspx, just like I would do for any other control:

<asp:SqlDataSource ID="sdsTest" .... ></asp:SqlDataSource>
<uc1:MyControl ID="controlTest" runat="server" DataSourceID="sdsTest" .. />

Didn't work!... So, found in internet (and tried) the following..

public String DataSourceID { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    if ((this.DataSourceID ?? "") != "")
    {
        SqlDataSource datasource = Utils.FindControl(Page, this.DataSourceID) as SqlDataSource;
        if (datasource != null)
        {
            myCheckList.DataSource = datasource;
            myCheckList.DataBind();
        }
    }
}

Even when the SqlDataSource is found, and the DataBind() is executed, my checkbox list is still not loaded. Am I missing something obvious?

Thanks in advance!

Well, after a good sleep , I found the problem, totally my fault and I will just post the correct code, just in case somebody needs to do something similar...

So, the problem was, my sqldatasource expected a parameter, and I could swear I declare it as a Session parameter from the beginning, BUT... I didn't, I declare it as a SIMPLE parameter (as I was not giving it a value, the sqldatasource was cancelling the select due to a null variable/parameter .

At the end, yes, just exposing the Checkboxlist's DataSourceID property is good enough!

In UserControl

public string DataSourceID
{
    get { return cbxOptions.DataSourceID; }
    set { cbxOptions.DataSourceID = value; }
}

In aspx

<uc1:MyControl ID="MyControl1" runat="server" DataSourceID="sdsTest" ... />
<asp:SqlDataSource ID="sdsTest" runat="server" 
                ConnectionString="..." SelectCommand="select [field] 
                                                      from [table] (nolock)
                                                      where customerid= @customerid">
   <SelectParameters>
        <asp:SessionParameter DbType="Int32" Name="customerid" SessionField="CustomerID" />
   </SelectParameters>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM