When using custom controls, client-side scripts are commonly used. That is, when the Render method of Control is rewritten, the client script can be directly output. But there are two bad points. 1. When multiple user controls are generated, multiple scripts are generated, resulting in confusion between scripts. 2. When a control calls a script, it will be called in the middle of another script file. Make a difference. The following method is the best method: Write a control similar to playing chess, code Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Namespace OwnControl
{
Public class ChessControl: Control
{
Protected override void Render (HtmlTextWriter writer)
{
Writer. addattriter( HtmlTextWriterAttribute. Border, "5px ");
Writer. RenderBeginTag (HtmlTextWriterTag. Table );
Writer. addattriter( HtmlTextWriterAttribute. Border, "5px ");
For (int row = 0; row <3; row ++)
{
Writer. RenderBeginTag (HtmlTextWriterTag. Tr );
For (int col = 0; col <3; col ++)
{
String clk = string. Format (
"OnClickCell (this, '{0}')", ClientID );
Writer. addattriter( HtmlTextWriterAttribute. Border, "5px ");
Writer. AddAttribute (HtmlTextWriterAttribute. Width, "20px ");
Writer. AddAttribute (HtmlTextWriterAttribute. Onclick, clk );
Writer. RenderBeginTag (HtmlTextWriterTag. Td );
Writer. Write ("& nbsp ;");
Writer. RenderEndTag ();
}
Writer. RenderEndTag ();
}
Writer. RenderEndTag ();
}
Protected override void OnInit (EventArgs e)
{
String sCode = "<script language = javascript> var g_grWentLast = new Object (); function OnClickCell (cell, idx) {if (cell. innerText = \ "\") {if (g_grWentLast [idx]) cell. innerText = 'O'; else cell. innerText = 'X'; g_grWentLast [idx] =! G_grWentLast [idx];} else cell. innerText = '';}; </script> ";
//
// This method uses keys to identify script blocks,
// You do not need to issue a script block to the output stream every time a different server control instance requests a script block.
// Using keys can also reduce the possibility of mutual interference between script blocks of different controls.
Page. RegisterClientScriptBlock ("CellCode", sCode );
}
}
}
Use of the interface:
<Useown: ChessControl ID = "user3" runat = "server"> </useown: ChessControl>