我在Visual Studio中使用Repeater
(asp.net和c#)。问题是,我不太确定如何正确格式化我的存储过程。
这是错误:
我的目标是让Repeater
显示表格中每列的标签和文本框。标签必须包含数据库中的DisplayName
。
以下是我要用于FormField
的表格Repeater
。
所以这是我对存储过程的想法:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spGetFormFields]
@TableName nvarchar,
@EventId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT COLUMN_NAME AS MyColumn
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
AND EventId = @EventId
AND Visible = 1
END
然而,由于我在EventId
和Visible
收到错误,这不太有效:
列名无效
所以这就是我在C#中所拥有的:
protected void Page_Load(object sender, EventArgs e)
{
//Make label names diff
//Control which columns are shown
//Style the labels and textboxes to css
DataTable table = new DataTable();
table.Columns.Add("MyColumn", typeof(string));
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 COLUMN_NAME AS MyColumn FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName AND EventId = @EventId AND Visible = 1");
sqlCmd2.Parameters.Add("@TableName", SqlDbType.NVarChar).Value = "FormField";
sqlCmd2.Parameters.Add("@EventId", SqlDbType.NVarChar).Value = "1";
sqlCmd2.ExecuteNonQuery();
using (SqlDataReader sqlReader = sqlCmd2.ExecuteReader())
{
while (sqlReader.Read())
{
DataRow tableRow = table.NewRow();
tableRow["MyColumn"] = sqlReader["MyColumn"].ToString();
table.Rows.Add(tableRow);
}
Repeater1.DataSource = table;
Repeater1.DataBind();
}
sqlConn2.Close();
}
}
}
}
我的C#代码在没有任何存储过程的情况下实现SQL(仍然会得到关于不存在的列的相同错误)。当然,我希望在我将其运行后添加存储过程,因此这是出于测试目的。
最后,这是asp.net标记:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="repeater.aspx.cs" Inherits="admin_repeater" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Label ID="lblTest" runat="server" Text='<%# Eval("MyColumn") %>'></asp:Label>
<asp:TextBox ID="textTest" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
答案 0 :(得分:5)
正如评论中所述,您正在查询INFORMATION_SCHEMA.COLUMNS
表,并且没有此类列EventId
&amp; Visible
那里。如果我理解正确你想根据条件从你的表中显示DisplayName
那么你可以直接这样做: -
SELECT DisplayName AS MyColumn
FROM [Events2].dbo.[FormField]
WHERE EventId = @EventId AND
Visible = 1