Passing custom object parameters in ObjectDataSource

Source: Internet
Author: User

Although SQLDataSource is relatively simple to use, its direct access to the database leads to a lack of flexibility in the use process.
In the development process, in order to realize the rational structure of the program and the good code reuse function, we usually use three layers of the Program for architecture. SQLDataSource, a function for directly connecting to the database, is difficult to implement in a three-tier architecture.
If the SQLDataSource control is not used, the functions of the GridView cannot be fully used. To solve this problem, Microsoft provides the ObjectDataSource control.

The ObjectDataSource control does not directly connect to databases. You can call business objects to perform database operations.

I. Several important attributes of the ObjectDataSource Control
SelectMethod: The method name called when the ObjectDataSource control executes the query.
DeleteMethod: name of the method called when the ObjectDataSource control is deleted.
UpdateMethod: name of the method called when the ObjectDataSource control is updated.
InsertMethod: name of the method called when the ObjectDataSource control executes the insert operation.

Ii. Several important methods of the ObjectDataSource Control
Select (): Call SelectMethod for query
Insert (): Call InsertMethod to Insert data.
Update (): Call UpdateMethod to Update
Delete (): Call DeleteMethod to Delete

3. Several important child elements of the ObjectDataSource Control
InsertParameters: Provides parameters for the InsertMethod method.
UpdateParameters: Provides parameters for the UpdateMethod method.
DeleteParameters: Provides parameters for the DeleteMethod method.
SelectParameters: Provides parameters for the SelectMethod method.
Iv. Examples
1. Configure the connection string
2. Write the business module (here I use the insert/update/delete/select statement of the database to replace it. In actual application, the business module is far more complex than this one)
The business function module uses the SQLDataSource object to read data. Of course, it can also use ADO. NET to read data.
Public class FruitDA
{
Private SqlDataSource sd;
Public FruitDA ()
{
Sd = new SqlDataSource ();
Sd. ConnectionString = System. Configuration. ConfigurationManager. ConnectionStrings ["conn1"]. ToString ();;
}
Public DataView select ()
{
Sd. SelectCommand = "select * from fruit ";
Sd. performancemode = sqlperformancemode. DataSet;
DataView ds = (DataView) sd. Select (DataSourceSelectArguments. Empty );
Return ds;
}
Public void update (string ids, string name, decimal price, string source, string stack)
{
Sd. UpdateCommand = "update fruit set name = @ name, price = @ price, source = @ source, stack = @ stack where ids = @ ids ";
Sd. UpdateParameters. Add ("ids", TypeCode. String, ids );
Sd. UpdateParameters. Add ("name", TypeCode. String, name );
Sd. UpdateParameters. Add ("price", TypeCode. Decimal, price. ToString ());
Sd. UpdateParameters. Add ("source", TypeCode. String, source );
Sd. UpdateParameters. Add ("stack", TypeCode. String, stack );
Sd. Update ();
}
Public void insert (string ids, string name, decimal price, string source, string stack)
{
Sd. InsertCommand = "insert into fruit (ids, name, price, source, stack) values (@ ids, @ name, @ price, @ source, @ stack )";
Sd. InsertParameters. Add ("ids", TypeCode. String, ids );
Sd. InsertParameters. Add ("name", TypeCode. String, name );
Sd. InsertParameters. Add ("price", TypeCode. Decimal, price. ToString ());
Sd. InsertParameters. Add ("source", TypeCode. String, source );
Sd. InsertParameters. Add ("stack", TypeCode. String, stack );
Sd. Insert ();
}
Public void delete (string ids)
{
Sd. DeleteCommand = "delete from fruit where ids = @ ids ";
Sd. DeleteParameters. Add ("ids", TypeCode. String, ids );
Sd. Delete ();
}
}
3. Configure ObjectDataSource and GridView to implement the update/select/delete function.
<Asp: GridView ID = "GridView1" runat = "server" AutoGenerateColumns = "False" DataKeyNames = "ids" performanceid = "s">
<Columns>
<Asp: CommandField ShowDeleteButton = "True" ShowEditButton = "True"/>
<Asp: BoundField DataField = "ids"/>
<Asp: BoundField DataField = "name"/>
<Asp: BoundField DataField = "price"/>
<Asp: BoundField DataField = "source"/>
<Asp: BoundField DataField = "stack"/>
</Columns>
</Asp: GridView>
<Asp: ObjectDataSource ID = "s" runat = "server" SelectMethod = "select" TypeName = "FruitDA" DeleteMethod = "delete" UpdateMethod = "update" InsertMethod = "insert">
<DeleteParameters>
<Asp: Parameter Name = "ids" Type = "String"/>
</DeleteParameters>
<UpdateParameters>
<Asp: Parameter Name = "ids" Type = "String"/>
<Asp: Parameter Name = "name" Type = "String"/>
<Asp: Parameter Name = "price" Type = "Decimal"/>
<Asp: Parameter Name = "source" Type = "String"/>
<Asp: Parameter Name = "stack" Type = "String"/>
</UpdateParameters>
<InsertParameters>
<Asp: ControlParameter Name = "ids" ControlID = "txtIds" Type = "String"/>
<Asp: ControlParameter Name = "name" ControlID = "txtName" Type = "String"/>
<Asp: ControlParameter Name = "price" ControlID = "txtPrice" Type = "Decimal"/>
<Asp: ControlParameter Name = "source" ControlID = "txtSource" Type = "String"/>
<Asp: ControlParameter Name = "stack" ControlID = "txtStack" Type = "String"/>
</InsertParameters>
</Asp: ObjectDataSource>
<Asp: TextBox ID = "txtIds" runat = "server"> </asp: TextBox>
<Asp: TextBox ID = "txtName" runat = "server"> </asp: TextBox>
<Asp: TextBox ID = "txtPrice" runat = "server"> </asp: TextBox>
<Asp: TextBox ID = "txtSource" runat = "server"> </asp: TextBox>
<Asp: TextBox ID = "txtStack" runat = "server"> </asp: TextBox> <br/>
<Asp: Button ID = "Button1" runat = "server" Text = "Insert" OnClick = "button#click"/>
4. Code for implementing the insert Function
Protected void button#click (object sender, EventArgs e)
{
S. Insert ();
}
(CHE Yanlu)

Custom Parameter
There are seven types of parameters in the SqlDataSource and ObjectDataSource controls, but these seven types of parameters sometimes cannot meet my needs.
Question:
In ObjectDataSource, the methods of business logic objects are called through four attributes: SelectMethod, InsertMethod, UpdateMethod, and DeleteMethod, parameters required for methods of business logic objects can be passed in through the corresponding Parameter attribute of the ObjectDataSource control. The Parameter sources and types of these Parameter parameters are fixed and cannot be solved in the following two cases.
A. parameters are not directly derived from controls, sessions, cookies, QueryString, etc. Instead, the attribute values of an object are used as the business logic method for passing parameters. How can we assign values to parameters.
B. The form parameter of the business logic method is not a common string, int, float type, but a custom type. How to assign values to parameters.
Custom Parameter:
To customize a Parameter, you need to write a class derived from the Parameter class and override its Evaluate method.
Public class CustomParameter: Parameter
{
Object obj; // The value of the parameter passed to the business logic object
Public object Value
{
Get {return obj ;}
Set {obj = value ;}
}
Public CustomParameter (){}
// Pass the parameter name and value, call the parent class constructor to assign values to the parameter name, and save the parameter value to obj.
Public CustomParameter (string name, object value): base (name)
{
Obj = value;
}
Public CustomParameter (string name, TypeCode type, object value): base (name, type)
{
Obj = value;
}
Public CustomParameter (CustomParameter original): base (original)
{
Obj = original. Value;
}
// It is automatically called when the DataSource control is bound, and the value of the Parameter object is updated and returned.
Protected override object Evaluate (HttpContext context, Control control)
{
Return Value;
}
}
Data access logic:
Public class FruitDB
{
Private SqlConnection conn;
Public FruitDB ()
{
Conn = new Conn (). Connection;
}
Public List <FruitData> select ()
{
List <FruitData> fruitlist = new List <FruitData> ();
SqlCommand cmd = conn. CreateCommand ();
Cmd. CommandText = "select * from fruit ";
Conn. Open ();
SqlDataReader dr = cmd. ExecuteReader ();
While (dr. Read ())
{
FruitData data = new FruitData (dr ["ids"]. toString (), dr ["name"]. toString (), decimal. parse (dr ["price"]. toString (), dr ["source"]. toString (), dr ["stack"]. toString (), dr ["image"]. toString ());
Fruitlist. Add (data );
}
Conn. Close ();
Return fruitlist;
}
Public void insert (FruitData fd)
{
SqlCommand cmd = conn. CreateCommand ();
Cmd. CommandText = "insert into fruit values (@ ids, @ name, @ price, @ source, @ stack, @ image )";
Cmd. Parameters. AddWithValue ("@ ids", fd. Ids );
Cmd. Parameters. AddWithValue ("@ name", fd. Name );
Cmd. Parameters. AddWithValue ("@ price", fd. Price );
Cmd. Parameters. AddWithValue ("@ source", fd. Source );
Cmd. Parameters. AddWithValue ("@ stack", fd. Stack );
Cmd. Parameters. AddWithValue ("@ image", fd. Image );
Conn. Open ();
Cmd. ExecuteNonQuery ();
Conn. Close ();
}
}
FruitData entity class:
Public class FruitData
{
Private string ids, name, price, source, stack, image;
Public string Ids
{
Get {return ids ;}
Set {ids = value ;}
}
Public string Name
{
Get {return name ;}
Set {name = value ;}
}
Public decimal Price
{
Get {return price ;}
Set {price = value ;}
}
Public string Source
{
Get {return source ;}
Set {source = value ;}
}
Public string Stack
{
Get {return stack ;}
Set {stack = value ;}
}
Public string Image
{
Get {return image ;}
Set {image = value ;}
}
Public FruitData (string ids, string name, decimal price, string source, string stack, string image)
{
This. ids = ids;
This. name = name;
This. price = price;
This. source = source;
This. stack = stack;
This. image = image;
}
} (CHE Yanlu)
Interface code:
<Asp: GridView ID = "GridView1" runat = "server" performanceid = "objectperformance1">
</Asp: GridView>
<Asp: ObjectDataSource ID = "objectperformance1" runat = "server" InsertMethod = "insertdb"
SelectMethod = "select" TypeName = "FruitDB">
</Asp: ObjectDataSource>
<Asp: TextBox ID = "txtIds" runat = "server"> </asp: TextBox>
<Asp: TextBox ID = "txtName" runat = "server"> </asp: TextBox>
<Asp: TextBox ID = "txtPrice" runat = "server"> </asp: TextBox>
<Asp: TextBox ID = "txtSource" runat = "server"> </asp: TextBox>
<Asp: TextBox ID = "txtStack" runat = "server"> </asp: TextBox>
<Asp: TextBox ID = "txtImage" runat = "server"> </asp: TextBox> <br/>
<Asp: Button ID = "Button1" runat = "server" Text = "Button" OnClick = "button#click"/>
Note: Do not add DataObjectTypeName = "FruitData" during insert. Otherwise, "No value can be inserted. Check the "values" error. During update and deletion, you must add the DataObjectTypeName = "FruitData" statement.
Post Code class:
// Construct a FruitData object
FruitData fd = new FruitData (txtIds. Text, txtName. Text, decimal. Parse (txtPrice. Text), txtSource. Text, txtStack. Text, txtImage. Text );
Objectperformance1.insertparameters. Clear ();
// Create a custom Parameter and input the created FruitData object
CustomParameter cp = new CustomParameter ("fd", fd );
// Add custom Parameters
Objectperformance1.insertparameters. Add (cp );
// Execute the query
Objectperformance1.insert ();

As we have seen in the previous tutorial, there are many options to pass the parameter value to the OjbectDataSource method. If the Parameter value is hard-coded and comes from a Web control on the page, or other sources that can be read by the Parameter object of the data source, this value can be bound to an input parameter without writing a line of code.

However, sometimes the Parameter values come from some sources that have not been computed in the built-in Parameter object of the data source. If our site supports our considerations, we may want the parameters to be based on the current login user. Alternatively, we can customize some of the methods before passing parameters to the implicit object of ObjectDataSource.

Whenever the Seelect method of ObjectDataSource is called, it will first trigger its Selecting event and then call the method of the implicit object of ObjectDataSource, after this is done, the Selected event of the ObjectDataSource is triggered (Figure 1 shows the sequence of these events ). You can set or change the parameter value in the event Delegate of the Selecting event.


Figure 1: The Selected and Selecting events of ObjectDataSource are triggered before and after the implicit object method of ObjectDataSource is called respectively.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.