My code works if I just have one tableRow, as such:
DataRow tableRow = table.NewRow();
tableRow["DisplayName"] = sqlReader["DisplayName"].ToString();
table.Rows.Add(tableRow);
If I add a second one, my Repeater displays nothing and doesn't work:
DataRow tableRow = table.NewRow();
tableRow["DisplayName"] = sqlReader["DisplayName"].ToString();
tableRow["ColumnName"] = sqlReader["ColumnName"].ToString();
table.Rows.Add(tableRow);
What is the proper code to add multiple of these?
EDIT:
I also tried this but didn't work:
DataRow tableRow = table.NewRow();
tableRow["DisplayName"] = sqlReader["DisplayName"].ToString();
table.Rows.Add(tableRow);
DataRow tableRow2 = table.NewRow();
tableRow2["ColumnName"] = sqlReader["ColumnName"].ToString();
table.Rows.Add(tableRow2);
And here is my Stored procedure code:
SELECT DisplayName AS DisplayName
FROM FormField
WHERE EventId = @EventId AND
FormId = @FormId AND
Visible = 1
UNION
SELECT ColumnName AS ColumnName
FROM FormField
WHERE EventId = @EventId AND
FormId = @FormId AND
Visible = 1
EDIT: C#
DataTable table = new DataTable();
table.Columns.Add("DisplayName", typeof(string));
table.Columns.Add("ColumnName", typeof(string));
using (SqlConnection sqlConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Events2"].ConnectionString))
{
sqlConn2.Open();
using (SqlCommand sqlCmd2 = new SqlCommand())
{
sqlCmd2.Connection = sqlConn2;
sqlCmd2.CommandType = CommandType.StoredProcedure;
sqlCmd2.CommandText = "spGetFormFields";
sqlCmd2.Parameters.Add("@EventId", SqlDbType.NVarChar).Value = eventId;
sqlCmd2.Parameters.Add("@FormId", SqlDbType.NVarChar).Value = formId;
sqlCmd2.ExecuteNonQuery();
using (SqlDataReader sqlReader = sqlCmd2.ExecuteReader())
{
while (sqlReader.Read())
{
DataRow tableRow = table.NewRow();
tableRow["DisplayName"] = sqlReader["DisplayName"].ToString();
table.Rows.Add(tableRow);
DataRow tableRow2 = table.NewRow();
tableRow2["ColumnName"] = sqlReader["ColumnName"].ToString();
table.Rows.Add(tableRow2);
}
RepeaterForm.DataSource = table;
RepeaterForm.DataBind();
}
sqlConn2.Close();
}
}
Something like this. The SqlDataAdapter
can fill a datatable automatically. It can also make inserts, updates and deletes if you need to but not as shown:
using (SqlConnection sqlConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Events2"].ConnectionString))
using (SqlCommand sqlCmd2 = new SqlCommand())
{
sqlConn2.Open();
sqlCmd2.Connection = sqlConn2;
sqlCmd2.CommandType = CommandType.StoredProcedure;
sqlCmd2.CommandText = "spGetFormFields";
sqlCmd2.Parameters.Add("@EventId", SqlDbType.NVarChar).Value = eventId;
sqlCmd2.Parameters.Add("@FormId", SqlDbType.NVarChar).Value = formId;
using (SqlDataAdapter da = new SqlDataAdapter(sqlCmd2))
{
da.Fill(Table);
RepeaterForm.DataSource = table;
RepeaterForm.DataBind();
}
sqlConn2.Close();
}