您强制使用属性返回 Class:TypeName
和DataObjectTypeName
of ObjectDataSource
。无需指定任何插入参数。
在您的文件夹中创建一个类,App_Code
将各个字段声明为可公开访问。例如:
类文件Country.cs
,声明字段
public class Country
{
public Country()
{
}
private string name;
public string Name
{
get { return name; }
set { name= value; }
}
private string capital;
public string Capital
{
get { return capital; }
set { capital= value; }
}
private string currency;
public string Currency
{
get { return currency; }
set { currency= value; }
}
private string iSOCode;
public string ISOCode
{
get { return iSOCode; }
set { iSOCode= value; }
}
}
现在在您的 Insert Method:AddCountry()
中,只需传递上述类的一个实例,如下所示。Class_variable_Name.Public_Field_Name
使用如下所示访问字段值 。
public void AddCountry(Country country)
{
// a sample code to access the values from Class instance passed in this method
string connString = WebConfigurationManager.ConnectionStrings["MyConnections"].ConnectionString;
SqlConnection con = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into Country(Name, Capital,Currency,ISOCode)
values(@Name,@Capital,@Currency,@ISOCode)";
cmd.Connection = con;
// Add the insert parameters
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 20));
// specify the values for insert parameters
// using the Country class passed as parameter to this method
cmd.Parameters["@Name"].Value = country.Name; // country.Public_Field_Name
cmd.Parameters.Add(new SqlParameter("@Capital", SqlDbType.NVarChar, 20));
cmd.Parameters["@Capital"].Value = country.Capital;
cmd.Parameters.Add(new SqlParameter("@Currency", SqlDbType.NVarChar, 20));
cmd.Parameters["@Currency"].Value = country.Currency;
cmd.Parameters.Add(new SqlParameter("@ISOCode", SqlDbType.NVarChar, 20));
cmd.Parameters["@ISOCode"].Value = country.ISOCode;
con.Open();
// execute the Insert Command
cmd.ExecuteNonQuery();
}
显然,在您的ObjectDataSource
控件中,您需要指定属性:TypeName
, DataObjectTypeName
.
1.)TypeName
表示包含数据访问方法的类的名称,表示包含您的方法的类文件:AddCountry()
2.) :获取或设置控件在、或数据操作中用于参数DataObjectTypeName
的类的名称,而不是从数据绑定控件传递单个值。在我们的例子中,这是上面创建的类。ObjectDataSource
update
insert
delete
Country
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
DataObjectTypeName="Country"
InsertMethod="AddCountry"
TypeName="CountryAccessMethods" <!-- assuming you have defined your Insert,
Update,Delete methods inside a class file named `CountryAccessMethods` -->
</asp:ObjectDataSource>