我有一个gridview,我想检查插入行但是我看到了这个错误:
CommandText属性尚未初始化。
我想我对strArrays的错误。我在这工作了两天
我该如何修复?
StringBuilder stringBuilder = new StringBuilder(string.Empty);
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString.ToString());
SqlCommand sqlCommand = new SqlCommand();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
int type = 2;
CheckBox chkUpdate = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chkSelect");
TextBox txtAmount = (TextBox)GridView1.Rows[i].Cells[5].FindControl("txtAmount");
if (chkUpdate != null)
{
if (chkUpdate.Checked)
{
string strID = GridView1.Rows[i].Cells[1].Text;
GridView1.Rows[i].FindControl("txtLocation")).Text;
string text = this.GridView1.Rows[i].Cells[1].Text;
string[] strArrays = new string[] { "INSERT INTO [OrderCancel]
([OrderID],
[Message],
[Type],
[RelationProductID],
[Amount])
VALUES(" ,
Request.QueryString["o"] ,
",'" , txtWhy.Text ,
"',",type.ToString(),",
" , strID , "," ,
txtAmount.Text , ");" };
stringBuilder.Append(string.Concat(strArrays));
//append update statement in stringBuilder
stringBuilder.Append(string.Concat(strArrays));
}
}
try
{
try
{
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = stringBuilder.ToString();
sqlCommand.Connection = sqlConnection;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
catch (SqlException sqlException)
{
throw new Exception(string.Concat("Error in Updation",
sqlException.Message));
}
}
finally
{
sqlConnection.Close();
}
答案 0 :(得分:1)
您的代码可以清理,您可以执行以下操作:
private readonly string dbConnection = "...";
private const string query = "... Column = @Column";
为了简洁起见,我添加了 ... ,它将与您的连接字符串和带参数的查询相关联。
var message = String.Empty;
using(var connection = new SqlConnection(dbConnection))
using(var command = new SqlCommand(query, dbConnection))
{
connection.Open();
command.CommandType = CommandType.Text;
command.Parameters.Add("@Column", SqlDbType.NVarChar).Value = message;
command.ExecuteNonQuery();
}
因此,小片段将位于方法内部,该方法将传递网格中的数据模型。然后,当您从Grid传递一个值时,您将构建模型并传递给将写入数据库的方法。
此外,当您使用StringBuilder
时,您还需要致电ToString();
以确保在您使用时string
而不是StringBuilder
。
答案 1 :(得分:0)
如果未设置commandText属性,通常会发生此错误。看看你的代码看起来你的stringbuilder变量没有设置。你试过在你的&#34; chkUpdate.Checked&#34;中加入一个断点吗?环?如果是,你可以发布在你的循环中构建的sql