Code analysis-the DataGrid enables auto-increment columns, single-choice, and multiple-choice

Source: Internet
Author: User

Turn: http://www.cnblogs.com/lovecherry/archive/2005/03/25/125487.html
Http://www.cnblogs.com/lovecherry/archive/2005/03/25/125492.html
The last time we added, deleted, modified, paginated, and dynamically modified the content for this DataGrid, we will analyze how to add auto-increment columns, single-choice, and multiple-choice features for it today.
First, let's take a look at the code that needs to be added based on the previous one:
(1) Implement Auto-increment Columns
You only need to add a template column in the foreground and bind ItemIndex + 1.
<Asp: TemplateColumn HeaderText = "select">
<ItemTemplate>
<% # Container. ItemIndex + 1%>
</ItemTemplate>
</Asp: TemplateColumn>
(2) single answer
Based on the above, add a radio for this column
<Asp: TemplateColumn HeaderText = "select">
<ItemTemplate>
<% # Container. ItemIndex + 1%>
<Input type = radio name = "rad" value = '<% # Container. ItemIndex + 1%>'>
</ItemTemplate>
</Asp: TemplateColumn>
The radio value is the auto-increment 1-PageSize.
Create a button (named "single choice") and add the following code to it:
This. Label1.Text = "selected row number:" + Request. Form ["rad"]. ToString ();
Although the selected row number is displayed in this simple step, after you press the button, the selection of radio cannot be retained because this radio is not runat = server, we need to place a hidden domain (runat = server) for this page to save the selected radio when clicking the button, add <input type = "hidden" id = "rd" runat = "server" name = "rd"> at the front end (Note: Do not add this to the DataGrid ), then add rd. value = Request. form ["rad"]. toString (); (if vs.net does not declare this HtmlInputHidden, add protected System. web. UI. htmlControls. htmlInputHidden rd ;). It has not been completed yet. Although the selected row number has been saved in HtmlInputHidden, you also need to set this radio to the selected status when loading the page, and change Page_Load ()
Private void Page_Load (object sender, System. EventArgs e)
{
String js = "";
Js + = "<script> \ r \ n ";
Js + = "function ld () {\ r \ n ";
Js + = "for (I = 0; I <document. getElementsByName ('rad '). length; I ++) \ r \ n ";
Js + = "if (document. getElementsByName ('rad ') [I]. value = ";
Js + = "document. getElementById ('" + this. rd. ClientID + "'). value )";
Js + = "document. getElementsByName ('rad ') [I]. checked = true \ r \ n ";
Js + = "} \ r \ n ";
Js + = "window. onload = ld \ r \ n ";
Js + = "</script> \ r \ n ";
This. RegisterStartupScript ("js", js );
If (! IsPostBack)
{
SetBind ();
}
}
The code above is analyzed below:

Q: Why not place the code in if (! IsPostBack?
A: if (! IsPostBack) (for details, see http://blog.csdn.net/lovecherry/archive/2005/02/25/301441.aspx.) In fact, you should put this code in if (! IsPostBack) {} else {put here}, because when loading the page for the first time, it is impossible to hide something in the domain (you select and click the button to submit when loading the page for the first time, how can there be something ?)

Q: What is \ r \ n?
A: This is a line feed, which does not affect code running. However, if a line feed is put, the presentation on the client can be clearer.

Q: Why should I use document. getElementById ('"+ this. rd. ClientID +"') for the rd value? The value does not use document. getElementById ('RD '). value?
A: You can use the latter here, but you need to know that rd is a server-side control. In some cases, the id displayed on the client is not the id you specified in aspx, but a control. clientID, for example, some server-side controls placed in the DataGrid. Check the source code and you can see that the id is similar to DataGrid1 _ ctl5_Hyperlink1, rather than the id you specified.

Q: Why not use RegisterClientScriptBlock?
A: It doesn't matter here. You can use RegisterClientScriptBlock because the JavaScript code is self-running (js ++ = "window. onload = ld \ r \ n ";), so the result will not be affected no matter the start or end of the form.

(3) Multi-Choice
First, add the following code (add a column) to the foreground)
<Asp: TemplateColumn>
<ItemTemplate>
<Input type = "hidden" id = "SelectedID" runat = "server"
Value = '<% # Container. ItemIndex %>' NAME = "SelectedID"/>
<Asp: CheckBox ID = "chkExport" Runat = "server"/>
</ItemTemplate>
</Asp: TemplateColumn>
Add a button to the page (named Multiple choices) and add the following code
Foreach (maid di in this. Maid)
{
If (CheckBox) di. FindControl ("chkExport"). Checked = true)
{
This. Label1.Text + = this. DataGrid1.DataKeys [int. Parse (HtmlInputHidden) di. FindControl ("SelectedID"). Value)] + "<br> ";
}
}
Click this button to display the value of the primary key of the data table corresponding to all selected items in the label position. You can use this value to perform database operations.

For example:
String s = "";
Foreach (maid di in this. Maid)
{
If (CheckBox) di. FindControl ("chkExport"). Checked = true)
{
S + = this. DataGrid1.DataKeys [int. Parse (HtmlInputHidden) di. FindControl ("SelectedID"). Value)] + ",";
}
}
SqlConnection conn = new SqlConnection (System. Configuration. ConfigurationSettings. deleettings ["conn"]);
SqlCommand comm = new SqlCommand ("delete from tb1 where ID in (", conn );
Comm. CommandText + = s. Substring (0, s. Length-1) + ")"; // Delete the last comma
Conn. Open ();
Comm. ExecuteNonQuery ();
Conn. Close ();
SetBind ();

You can add two more buttons, one is "select all" and the other is "cancel all" to add the following code respectively.
Foreach (maid di in this. Maid)
{
(CheckBox) di. FindControl ("chkExport"). Checked = true;
}

Foreach (maid di in this. Maid)
{
(CheckBox) di. FindControl ("chkExport"). Checked = false;
}

The above code is analyzed as follows:

Q: If you select all or cancel all selected buttons, they are submitted to the server. Can you do this without submitting them?
A: First of all, it is clear that the checkbox in the template column is runat = server. As mentioned above, the rendering id on the client is similar to that on the DataGrid1 _ ctl9_chkExport, therefore, when using the client js, we can only use the control. clientID. If it is obtained during Page_Load, it cannot be obtained because the checkbox is placed in the DataGrid template column and the DataGrid has not been Created during Page_Load. The solution is to use a hidden domain on the server to save multiple projects, and then replace <asp: CheckBox> in the template column with the checkbox of html, during selection, you can change the values in the hidden fields (through js, so the page is not submitted). When you click the multiple selection button, you can obtain the selected project by reading the values in the hidden fields, this is actually a transformation from a server-based code to a client-oriented code. Sometimes, it is very convenient for the server to interact with the client by hiding the domain. In subsequent articles, we will detail multiple cross-page selections, as well as examples of client selection and cancellation.

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.