简体   繁体   English

事件顺序背后的SqlDataSource代码

[英]SqlDataSource Code Behind Event Order

I have an SqlDataSource, a Gridview and a DropDownList on the same page. 我在同一页面上有一个SqlDataSource,一个Gridview和一个DropDownList。 The DropDownList selection is associated with a set of SelectCommands , UpdateCommands , and DeleteCommands so that I can take advantage of the GridView AutoGenerateEditButton="true" and AutoGenerateUpdateButton="true" mechanism. DropDownList选项与一组SelectCommandsUpdateCommands和DeleteCommands相关联,这样我就可以利用GridView AutoGenerateEditButton =“true”和AutoGenerateUpdateButton =“true”机制。

Page_Load
{
  switch(ddl.SelectedItem.Text)
  {
     case "A":
       sqlDS.SelectCommand = "Select * From A";
       sqlDS.UpdateCommand = "Update A Set Name = @Name WHERE ID = @ID";
       sqlDS.DeleteCommand = "Delete A WHERE ID = @ID";
       break;
     ...
  }

  sqlDS.DataBind();
  grd.DataSourceID = sqlDS.ID;
  grd.DataBind();
}

How or at what point do I need to add Parameters? 我需要如何或在什么时候添加参数? Is it automatic? 它是自动的吗? I basically just want the ability to update and delete columns from a table. 我基本上只是希望能够更新和删除表中的列。 I want to do all of this in the actual .cs file, as opposed to within the .aspx file as I'd like to make it more dynamic eventually; 我想在实际的.cs文件中完成所有这些操作,而不是在.aspx文件中,因为我希望最终使它更具动态性; but for now I just want to get the basics down. 但是现在我只想把基础知识搞定。 I suspect that I may have the DataBind() logic in the inappropriate event because I don't fully understand the order of events associated with the data binding. 我怀疑我可能在不适当的事件中有DataBind()逻辑,因为我不完全理解与数据绑定相关的事件的顺序。

The queries are not complicated and involve no joins or views; 查询并不复杂,不涉及连接或视图; they are simple SELECTs over single tables. 它们是单个表上的简单SELECT。

Edit : It does appear that if you use AutoGenerateColumns="true" on the GridView and populate via SqlDataSource, it will automatically bind the values of the controls by name to the appropriate parameters in the SQL query without any extra code. 编辑 :看起来如果你在GridView上使用AutoGenerateColumns =“true”并通过SqlDataSource填充,它会自动将控件的值按名称绑定到SQL查询中的相应参数,而不需要任何额外的代码。 However, we have to use GetInsertCommand(true) , etc. so that the commands use the column names (see code below where I show how to use SqlCommandBuilder . There are a few gotchas, however as I've discovered in testing: 但是,我们必须使用GetInsertCommand(true)等,以便命令使用列名称(请参阅下面的代码,我将展示如何使用SqlCommandBuilder 。有一些问题,但正如我在测试中发现的那样:

  • You need to set the DataKeyNames of your GridView 您需要设置GridView的DataKeyNames
  • You'll need to set OldValuesParameterFormatString="Original_{0}" on your sqlDS. 您需要在sqlDS上设置OldValuesParameterFormatString="Original_{0}"
  • You'll need scb.ConflictOption = System.Data.ConflictOption.OverwriteChanges; 你需要scb.ConflictOption = System.Data.ConflictOption.OverwriteChanges; on your SqlCommandBuilder if you want to just update without comparing old values. 在你的SqlCommandBuilder如果你想在不比较旧值的情况下进行更新。
  • It appears that if you are populating Select/Update/DeleteCommand on a SqlDataSource programmatically, you have to do it on every postback. 看来,如果以编程方式在SqlDataSource上填充Select / Update / DeleteCommand,则必须在每次回发时执行此操作。

However, in case you need to customize, the SqlDataSource control provides the events Inserting , Updating , Deleting that you can use to populate the parameters before the SQL actions are taken on the database: 但是,如果需要自定义, SqlDataSource控件提供可在数据库上执行SQL操作之前填充参数的事件InsertingUpdatingDeleting

sqlDS.Updating += new SqlDataSourceCommandEventHandler(sqlDS_Updating);

protected void sqlDS_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
    e.Command.Parameters["@Name"].Value = // retrieve value from user entry
}

The same kind of thing can be done in the Inserting and Deleting events via the e.Command.Parameters[...] access. 通过e.Command.Parameters[...]访问可以在InsertingDeleting事件中完成同样的事情。


Note that you can also generate the appropriate Delete/Insert/Update command automatically using the SqlCommandBuilder class so that you don't have to build a giant switch statement containing all of your tables. 请注意,您还可以使用SqlCommandBuilder类自动生成相应的Delete / Insert / Update命令,这样您就不必构建包含所有表的巨型switch语句。 Here's an example: 这是一个例子:

string tableName = ddl.SelectedValue;
string connectionString = ConfigurationManager
    .ConnectionStrings["MyConnectionString"].ConnectionString;
string select = "SELECT * FROM [" + tableName + "]";
SqlDataAdapter sda = new SqlDataAdapter(select, connection);
SqlCommandBuilder scb = new SqlCommandBuilder(sda);

sqlDS.SelectCommand = select;
sqlDS.InsertCommand = scb.GetInsertCommand(true).CommandText;
sqlDS.UpdateCommand = scb.GetUpdateCommand(true).CommandText;
sqlDS.DeleteCommand = scb.GetDeleteCommand(true).CommandText;

This will of course require that all of your tables have primary keys that can be used to generate the relevant update and delete statements. 这当然要求所有表都具有可用于生成相关更新和删除语句的主键。 If not, you will get an exception about dynamic SQL generation. 如果没有,您将获得有关动态SQL生成的例外。 Even if you don't like this method because of the run-time cost of looking up the schema on the database engine, you could always pre-generate them all with a T4 template instead of typing them all in by hand. 即使您不喜欢这种方法,因为在数据库引擎上查找模式的运行时成本,您总是可以使用T4模板预先生成它们,而不是手动输入它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM