Friday, February 19, 2010

ValidatorCallOutExtender in TextBox in Gridview

Place a gridview with two itemtemplate.
One template to keep TextBox, RequiredFieldValidator and ValidatorCalloutExtender.
Second template will contain Button. Copy and paste the below code on the aspx page

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">




<asp:TextBox runat="server" ID="MyTextBox"

BorderStyle="solid" BorderWidth="1px" BorderColor="#a9a9a9" />

<asp:RequiredFieldValidator runat="server" ID="MyReq"

ControlToValidate="MyTextBox" Display="None"

ErrorMessage="<b>Required Field Missing</b><br />A name is required." />

<ajaxToolkit:ValidatorCalloutExtender runat="Server" ID="NReqE1"


HighlightCssClass="validatorCalloutHighlight" />





<asp:Button runat="server" ID="btn" Text="Testing"

BorderStyle="solid" BorderWidth="1px" BorderColor="#a9a9a9"/>



<asp:BoundField DataField="lastName" HeaderText="Last Name" />




Now we need to bind TextBox, RequiredFieldValidator and Button with validation group. ValidationGroup name should be unique for each pair of TextBox and Button. To give unique name to ValidationGroup of each pair of TextBox and Button, we need to bind the TextBox and Button GridView1_RowDataBound. Refer below code.

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)


   if (e.Row.RowType == DataControlRowType.DataRow)


      TextBox tbx = (TextBox)e.Row.FindControl("MyTextBox");

      RequiredFieldValidator rfv = (RequiredFieldValidator)   


      Button btn = (Button)e.Row.FindControl("btn");

      string validationGroupText = "ValidationTest" + (e.Row.DataItemIndex + 1).ToString();

      tbx.ValidationGroup = validationGroupText;

      rfv.ValidationGroup = validationGroupText;

      btn.ValidationGroup = validationGroupText;




Compile and run the application.

Happy Coding :)

No comments:

Site Meter