Search code examples
c#asp.netascx

Retrieving check box name (value) from a table in SQL database into ascx file


I have tab names stored in a table named 'Importtabs' in my SQL database. Instead of hard coding the name of tabs i am importing i want to retrieve the names from the above mentioned table and set them as values for my checkbox list on the ascx side. Here is the hardcoded version that i was earlier using:

<div style="overflow: auto;"> 
<asp:CheckBoxList ID="CheckBoxList1" BorderStyle="None" runat="server" RepeatColumns="3">
<asp:ListItem>All Temporary Differences</asp:ListItem>
<asp:ListItem>All Permanent Differences</asp:ListItem>
<asp:ListItem>All BS Only Differences</asp:ListItem>
<asp:ListItem>RTA Temp</asp:ListItem>
<asp:ListItem>RTA Perm</asp:ListItem>
<asp:ListItem>RTA Temp Other</asp:ListItem>
<asp:ListItem>RTA Perm Other</asp:ListItem>
<asp:ListItem>RTA Other Expense</asp:ListItem>
</div>

How can i do a similar thing as shown above but using the names ( 'All Temporary Differences', 'All Permanent Differences' etc ) from the 'Importtabs' table in my Database. Please help.


Solution

  • Assuming you already know how to retrieve data from a database, this code can be used to put that data into the CheckBoxList

    protected void Page_Load(object sender, EventArgs e)
    {
        // do not rebind the list if this is a postback; user input would be lost 
        if (this.IsPostBack)
        {
            return;
        }
        CheckBoxList1.DataSource = GetValues();
        CheckBoxList1.DataBind();
    }
    
    private string[] GetValues()
    {
        // get data from database, with 'select <columnName> from Importtabs'
        // populate array
        // return values as a string[]
    }
    

    That will result in a lot of hits to your database, so you might want to run the GetValues() method once and then cache the results.


    Links for Caching and SqlConnection