我正在使用Visual Studio(asp.net和c#)。我的Repeater显示我想要的每一行的复选框和标签。现在我想把那些被检查并在我的表中插入新行。
一切似乎都没问题,但是当我检查我的数据库时,没有添加任何行。
存储过程:
ALTER PROCEDURE [dbo].[spSetFormFields]
@FormId int,
@EventId int,
@ColumnName nvarchar(255),
@Visible bit,
@ColumnOrder int,
@DisplayName nvarchar(255)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO FormField(FormId, EventId, ColumnName, Visible, ColumnOrder, DisplayName)
VALUES (@FormId, @EventId, @ColumnName, @Visible, @ColumnOrder, @DisplayName)
END
C#
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["Events2"].ConnectionString))
{
sqlConn.Open();
//Insert text into db
using (SqlCommand sqlCmd2 = new SqlCommand())
{
//If checked, visible = true
foreach (RepeaterItem rpItem in Repeater1.Items)
{
int i = 1;
CheckBox chkbx = rpItem.FindControl("Checkbox1") as CheckBox;
Label lbl = rpItem.FindControl("lblTest") as Label;
if (chkbx.Checked)
{
sqlCmd2.CommandType = CommandType.StoredProcedure;
sqlCmd2.CommandText = "spSetFormFields";
sqlCmd2.Parameters.Add("@EventId", SqlDbType.Int).Value = 2;
sqlCmd2.Parameters.Add("@FormId", SqlDbType.Int).Value = 2;
sqlCmd2.Parameters.Add("@ColumnName", SqlDbType.NVarChar).Value = lbl.Text;
sqlCmd2.Parameters.Add("@DisplayName", SqlDbType.NVarChar).Value = lbl.Text;
sqlCmd2.Parameters.Add("@Visible", SqlDbType.Bit).Value = 1;
sqlCmd2.Parameters.Add("@ColumnOrder", SqlDbType.NVarChar).Value = i;
i++;
}
}
else
{
//do nothing
}
}
}
}
答案 0 :(得分:1)
您需要清除参数并执行查询。像这样:
sqlCmd2.Parameters.Clear(); // Add This line
sqlCmd2.Parameters.Add("@EventId", SqlDbType.Int).Value = 2;
sqlCmd2.Parameters.Add("@FormId", SqlDbType.Int).Value = 2;
sqlCmd2.Parameters.Add("@ColumnName", SqlDbType.NVarChar).Value = lbl.Text;
sqlCmd2.Parameters.Add("@DisplayName", SqlDbType.NVarChar).Value = lbl.Text;
sqlCmd2.Parameters.Add("@Visible", SqlDbType.Bit).Value = 1;
sqlCmd2.Parameters.Add("@ColumnOrder", SqlDbType.NVarChar).Value = i;
sqlCmd2.ExecuteNonQuery(); // Add This line