我想使用ObjectDatasource从文本框中插入数据。 ObjectDataSource绑定到一个gridview,但只显示某些计算列。文本框用于输入所有基本输入。 ObjectDatasource删除&选择命令(GridView上的链接按钮)正在工作。不过,我在插入命令时遇到了问题。我无法弄清楚如何将文本框中的数据作为参数传递给ObjectDataSource插入ObjectDatasource传递参数
编辑:使用下面的代码,正在插入一条记录。参数正在通过。 odssMain.Insert()给出错误:“未将对象引用设置为对象的实例”。 编辑:为什么我得到这个错误?
此外,ObjectDataSource一直很奇怪。发生错误后,我必须在ODS向导中再次重新配置插入方法,因为该方法将为空。
ASP.NET 3.5 & SQL 2008,VS 2008
这里是我的代码:
<asp:ObjectDataSource ID="odsMain" runat="server"
SelectMethod="SelectMain" DeleteMethod="DeleteMain"
InsertMethod="InsertMain" UpdateMethod="UpdateMain"
OldValuesParameterFormatString="original_{0}" TypeName="MainDB" >
.......
<InsertParameters>
<asp:Parameter Name="Quantity" Type="Int32" />
</InsertParameters>
DAL FILE:
[DataObjectMethod(DataObjectMethodType.Insert)]
public static int InsertMain(int Quantity)/
{
SqlConnection con = new SqlConnection(GetConnectionString());
string strQuery = "INSERT INTO t_Main (Quantity) VALUES (@Quantity)";
SqlCommand cmd = new SqlCommand(strQuery, con);
cmd.Parameters.AddWithValue("@Quantity", Quantity);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
CODE BEHIND FILE:
protected void btnSaveAnalysis_Click(object sender, EventArgs e)
{
odsMain.InsertParameters.Clear();
//Store parameters with values to the collection
odsMain.InsertParameters.Add(new Parameter ("Quantity", TypeCode.Int32, iQuantity.ToString()));
//Diferent ways that I tried. Still not working
//odsMain.InsertParameters.Add("Quantity", iQuantity.ToString());
//odsMain.InsertParameters["Quantity"].DefaultValue = iQuantity.ToString();
odsMain.Insert();
}
是的,我没有看到类似这样的例子。 – user450143
但是,Customer.InsertParameters [“FirstName”]。DefaultValue = strFirstName行给我一个运行时错误。 – user450143