Home > ASP.Net > Validate Dropdownlist inside Gridview

Validate Dropdownlist inside Gridview


Hi

try this example to validate Dropdownlist inside Gridview control that user should select value

<asp:GridView ID="GridView1" AutoGenerateColumns="False" ShowHeader="True" runat="server"

OnRowDataBound="GridView1_RowDataBound">
 <Columns>
  <asp:TemplateField HeaderText="DropDownList">
   <ItemTemplate>
    <asp: DropDownList id="DropDownList1" runat="server">
     <asp:listitem value="0">Select one</asp:listitem>
     <asp:listitem value="1">Item 1</asp:listitem>
     <asp:listitem value="2">Item 2</asp:listitem>
     <asp:listitem value="3">Item 3</asp:listitem>
    </asp: DropDownList>
   </ItemTemplate>
  </asp:TemplateField>
  <asp:TemplateField HeaderText="Button">
   <ItemTemplate>
    <asp:Button id="addButton" runat="server" text="Add"></asp:Button>
   </ItemTemplate>
  </asp:TemplateField>
 </Columns>
</asp:GridView>

<script type="text/javascript">
<!--
function onAddButtonClick(dropDownListId)
{
 var dropDownListRef = document.getElementById(dropDownListId);

 if ( dropDownListRef.value == '0' )
 {
  alert('Please select something from the DropDownList');
  dropDownListRef.focus();
  dropDownListRef.select();
  return false;
 }

 return true;
}
// -->
</script>

in code behind:-

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
  Button gridButton = (Button)e.Row.FindControl("addButton");
  DropDownList gridDropDownList = (DropDownList)e.Row.FindControl("DropDownList1");

  if ( (gridButton != null) && (gridDropDownList != null) )
  {
   string clickHandler = string.Format("return onAddButtonClick('{0}');",gridDropDownList.ClientID);
   gridButton.Attributes.Add("onclick", clickHandler);

  }
 }
}

Good Luck

Advertisements
Categories: ASP.Net
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: