简体   繁体   中英

How can bind data to repeater control in asp.net c#?

I am binding data to repeater control from database of company. I am trying to fetch company name from database and want to show as label, but it is not working.

My C# code is:

string conn_string = ConfigurationManager.ConnectionStrings["UPOneConn"].ConnectionString;
SqlConnection con = new SqlConnection(conn_string);
con.Open();
string ComSelectCompanyDataStr = "Select Company_Name from Company_Details where Company_ID = '8' ";
SqlCommand ComSelectCompanyData = new SqlCommand(ComSelectCompanyDataStr, con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = ComSelectCompanyData;
DataTable dt = new DataTable();
da.Fill(dt);

Repeater1.DataSource = dt;
Repeater1.Visible = true;   
con.Close();

and my design code:

<div id="company_container">
        <asp:Repeater ID="Repeater1" runat="server">
            <HeaderTemplate>
                <table>
                    <tr>
                        <td>
                            <asp:Label ID="Label1" runat="server"><%# Eval ("Company_Name") %></asp:Label></td>
                    </tr>
                </table>
            </HeaderTemplate>
            <ItemTemplate>
                <tr>
                    <td></td>
                </tr>            
            </ItemTemplate>
            <FooterTemplate>
                </table>
            </FooterTemplate>
        </asp:Repeater>
    </div>

You must add:

Repeater1.DataBind();

after

Repeater1.DataSource = dt;

So:

Repeater1.DataSource = dt;
Repeater1.DataBind();

And your repeater hes not any item in its ItemTemplate? You should set that like:

<ItemTemplate>
            <tr>
                <td><%# Eval ("Company_Name") %></td>
            </tr>            
        </ItemTemplate>

And you sql query has bad syntax (If company id is int).

change that to this:

"Select Company_Name from Company_Details where Company_ID = 8";

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