I want to have a label and checkbox for each row in from my query.
I needed to get the number of records from my sql query, but I read that SELECT statements will not work with int numberOfRecords = sqlCmd2.ExecuteNonQuery();. So what should I do instead to get the number of records selected from my query (see code below)?
Is this code enough to do what I need to generate labels and checkboxes from a db? Or am I missing something?
Side Note: I do not want to use the Repeater Control. I have tried it, and it isn't robust enough as I program more complicated pages.
ASP
<table>
<tr>
<td>
<asp:Label ID="LabelFormFields" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:CheckBoxList ID="CheckBoxListFormFields" runat="server">
</asp:CheckBoxList>
</td>
</tr>
</table>
C#
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection sqlConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Events2"].ConnectionString))
{
sqlConn2.Open();
using (SqlCommand sqlCmd2 = new SqlCommand())
{
sqlCmd2.Connection = sqlConn2;
sqlCmd2.CommandType = System.Data.CommandType.Text;
sqlCmd2.CommandText = string.Format("SELECT DisplayName FROM FormField WHERE EventId = 1 AND Visible = 0 ORDER BY ColumnOrder ASC;");
sqlCmd2.ExecuteNonQuery();
int numberOfRecords = //something here;
using (SqlDataReader sqlReader = sqlCmd2.ExecuteReader())
{
while (sqlReader.Read())
{
for (int i = 0; i < numberOfRecords; i++)
{
var PanelFormFields = new Panel();
var LabelFormFields = new Label();
var ListItemFormFields = new ListItem();
LabelFormFields.Text = sqlReader["DisplayName"].ToString();
CheckBoxListFormFields.Items.Add(new ListItem(sqlReader["DisplayName"].ToString(), "C"));
PanelFormFields.Controls.Add(LabelFormFields);
PanelFormFields.Controls.Add(CheckBoxListFormFields);
}
}
}
sqlConn2.Close();
}
}
}
Aucun commentaire:
Enregistrer un commentaire