In network development, it is often necessary to use ASP. NET and JavaScript For joint control. In this article, we will use the DataGrid for Data Binding and use JavaScript to control the color of the row when the checkbox is selected.
First, create a DataGrid Control on the page and set its template.
<Asp: DataGrid id = "datagrid1" runat = "server" autogeneratecolumns = "false">
<Columns>
<Asp: templatecolumn>
<Itemtemplate>
<Asp: checkbox id = "checkbox1" runat = "server"> </ASP: checkbox>
<Asp: Label runat = "server" text = '<% # databinder. eval (container, "dataitem") %>'> </ASP: Label>
</Itemtemplate>
</ASP: templatecolumn>
</Columns>
</ASP: DataGrid>
Second, compile the Javascript script function in
<SCRIPT>
Function checkme (OBJ, TR ){
If (obj. Checked)
Tr. style. backgroundcolor = 'blue ';
Else
Tr. style. backgroundcolor = '';
}
</SCRIPT>
Third, bind data to the DataGrid in the page_load event and associate it with the Javascript script of the checkbox.
Private void page_load (Object sender, system. eventargs E)
{
// Put user code to initialize the page here
If (! Ispostback)
{
Databind ();
}
}
Private void databind ()
{
Arraylist arr = new arraylist ();
Arr. Add ("News synthesis ");
Arr. Add (" ");
Arr. Add ("movie ");
Arr. Add ("education ");
Arr. Add ("drama ");
Arr. Add ("military ");
Arr. Add ("Sports ");
Datagrid1.datasource = arr;
Datagrid1.databind ();
Int I;
For (I = 0; I <datagrid1.items. Count; I ++ ){
Checkbox CB;
CB = (checkbox) datagrid1.items [I]. findcontrol ("checkbox1 ");
Datagrid1.items [I]. Attributes. Add ("ID", "TR" + I. tostring ());
CB. Attributes. Add ("onclick", "checkme (this, TR" + I. tostring () + ");");
}
}
Fourth, runProgram. After the program runs, a checkbox control is displayed in front of each row of the DataGrid Control. Select this control. The background color of this row changes to blue. deselect the control and the color of this row is restored to the initial state.