How to perform validation on the controls which is inside the Radgrid control?
How to perform validation on the controls which is inside the Radgrid control? In this article i am going to explain the steps of validating controls during the add and the edit mode
inside the Radgrid control.
In this articel we will see how to perform the validations on the controls which is inside the redgrid control. i.e. the controls which we take inside the radgrid controls like textbox how can we perform validations on it during the add and the edit mode.
For this we first take RadGrid Control:
<telerik:RadGrid ID="rgdEmployee" runat="server" GridLines="None" AllowAutomaticDeletes="false"
OnItemCreated="rgdEmployee_ItemCreated" Visible="true" AllowAutomaticInserts="false"
PageSize="5" AllowAutomaticUpdates="false" AllowPaging="True" AutoGenerateColumns="False"
EnableEmbeddedSkins="true" OnItemCommand="rgdEmployee_ItemCommand" OnItemDataBound="rgdEmployee_ItemDataBound"
OnNeedDataSource="rgdEmployee_NeedDataSource" OnUpdateCommand="rgdEmployee_UpdateCommand">
<PagerStyle Mode="NextPrevAndNumeric"></PagerStyle>
<MasterTableView Width="100%" CommandItemDisplay="Top" InsertItemPageIndexAction="ShowItemOnCurrentPage"
Name="Master" DataKeyNames="Id" HorizontalAlign="NotSet" EditMode="EditForms"
AutoGenerateColumns="False" CommandItemSettings-ShowRefreshButton="false">
<Columns>
<telerik:GridBoundColumn DataField="EmployeeName" HeaderText="EmployeeName" SortExpression="EmployeeName"
UniqueName="EmployeeName" ColumnEditorID=" GridTextBoxColumnEditor1" MaxLength="200"
Visible="true" ItemStyle-CssClass="rgEditForm">
</telerik:GridBoundColumn>
<telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditEmployee"
HeaderText="Edit" ItemStyle-Width="200px" ItemStyle-Wrap="false">
</telerik:GridEditCommandColumn>
<telerik:GridButtonColumn ConfirmText="" ConfirmDialogType="RadWindow" ConfirmTitle="Delete"
CommandName="DeleteEmployee" ButtonType="ImageButton" UniqueName="DeleteEmployee"
HeaderText="Delete">
</telerik:GridButtonColumn>
</Columns>
<CommandItemSettings ShowRefreshButton="false" />
</MasterTableView>
</telerik:RadGrid>
<telerik:GridTextBoxColumnEditor ID="GridTextBoxColumnEditor1" runat="server" TextBoxStyle-Width="200px" />
<telerik:RadWindowManager ID="RadWindowManager1" runat="server">
</telerik:RadWindowManager>
Here i have used just one column for demo purpose. Similarly yo ucan add more controls.
Now First we bind the Gridview from the database:
string connection = ConfigurationManager.ConnectionStrings["Databaseconnstring"].ToString();
SqlConnection con = null;
public bool? isdetail = false;
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand();
con.Open();
if (!IsPostBack)
{
EmployeeNameGridBind();
}
}
// this code will perform th inset,update and delete operations.
protected void rgdEmployee_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
try
{
if (e.CommandName == "Update")
{
GridEditableItem editedItem = e.Item as GridEditableItem;
GridEditManager editMan = editedItem.EditManager;
int Employeeid = Convert.ToInt16(((GridEditFormItem)e.Item).GetDataKeyValue("Id"));
SqlCommand mySqlUpdate = new SqlCommand("update Employee set EmployeeName = @en where Id = @id", con);
mySqlUpdate.Parameters.Add("@en", SqlDbType.VarChar).Value = Convert.ToString(((GridTextBoxColumnEditor)(editMan.GetColumnEditor("EmployeeName"))).Text);
mySqlUpdate.Parameters.Add("@id", SqlDbType.Int).Value = Employeeid;
int i = mySqlUpdate.ExecuteNonQuery();
if (i > 0)
{
rgdEmployee.MasterTableView.ClearEditItems();
EmployeeNameGridBind();
rgdEmployee.Rebind();
Label1.Text = "Record updated";
}
else
{
((GridTextBoxColumnEditor)(editMan.GetColumnEditor("EmployeeName"))).Text = ((GridTextBoxColumnEditor)(editMan.GetColumnEditor("EmployeeName"))).Text;
Label1.Text = "record not updated";
rgdEmployee.MasterTableView.EditMode = GridEditMode.EditForms;
rgdEmployee.Rebind();
}
}
else if (e.CommandName == "DeleteEmployee" && e.Item.OwnerTableView.Name == "Master")
{
GridDataItem item = (GridDataItem)e.Item;
int EmployeeIds = Convert.ToInt32(item.GetDataKeyValue("Id"));
SqlCommand mySqlDelete = new SqlCommand("update Employee set IsActive=0 where Id=@id", con);
mySqlDelete.Parameters.Add("@id", SqlDbType.Int).Value = EmployeeIds;
int i = mySqlDelete.ExecuteNonQuery();
if (i > 0)
{
EmployeeNameGridBind();
rgdEmployee.Rebind();
}
else
Label1.Text = "Employee not deleted";
}
else if (e.CommandName == "InitInsert" && e.Item.OwnerTableView.Name == "Master")
{
hdnIsAddEdit.Value = "true";
rgdEmployee.MasterTableView.ClearEditItems();
}
else if (e.CommandName == "PerformInsert" && e.Item.OwnerTableView.Name == "Master")
{
GridEditableItem editedItem = e.Item as GridEditableItem;
GridEditManager editMan = editedItem.EditManager;
string EmployeeName = Convert.ToString(((GridTextBoxColumnEditor)(editMan.GetColumnEditor("EmployeeName"))).Text);
SqlCommand mySqlUpdate = new SqlCommand("Insert into Employee(EmployeeName) values(@an)", con);
mySqlUpdate.Parameters.Add("@an", SqlDbType.VarChar).Value = EmployeeName;
int i = mySqlUpdate.ExecuteNonQuery();
if (i > 0)
{
e.Item.OwnerTableView.IsItemInserted = false;
EmployeeNameGridBind();
Label1.Text = "Employee inserted";
}
else
{
((GridTextBoxColumnEditor)(editMan.GetColumnEditor("EmployeeName"))).Text = ((GridTextBoxColumnEditor)(editMan.GetColumnEditor("EmployeeName"))).Text;
Label1.Text = "Employee not inserted";
rgdEmployee.MasterTableView.EditMode = GridEditMode.EditForms;
rgdEmployee.Rebind();
}
}
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
protected void rgdEmployee_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
EmployeeNameGridBind();
}
protected void rgdEmployee_UpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
try
{
GridEditableItem editedItem = e.Item as GridEditableItem;
GridEditManager editMan = editedItem.EditManager;
int Employeeid = Convert.ToInt16(((GridEditFormItem)e.Item).GetDataKeyValue("Id"));
SqlCommand mySqlUpdate = new SqlCommand("update Employee set EmployeeName = @an where Id = @id", con);
mySqlUpdate.Parameters.Add("@an", SqlDbType.VarChar).Value = Convert.ToString(((GridTextBoxColumnEditor)(editMan.GetColumnEditor("EmployeeName"))).Text);
mySqlUpdate.Parameters.Add("@id", SqlDbType.Int).Value = Employeeid;
int i = mySqlUpdate.ExecuteNonQuery();
if (i > 0)
{
rgdEmployee.MasterTableView.ClearEditItems();
EmployeeNameGridBind();
rgdEmployee.Rebind();
Label1.Text = "des";
}
else
{
((GridTextBoxColumnEditor)(editMan.GetColumnEditor("EmployeeName"))).Text = ((GridTextBoxColumnEditor)(editMan.GetColumnEditor("EmployeeName"))).Text;
Label1.Text = "des1";
rgdEmployee.MasterTableView.EditMode = GridEditMode.EditForms;
rgdEmployee.Rebind();
}
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
private void EmployeeNameGridBind()
{
string query = "select * from Employee where isactive=1";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
da.Fill(dt);
rgdEmployee.DataSource = dt;
}
protected void rgdEmployee_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
try
{
if (e.Item is GridCommandItem)
{
GridCommandItem commandItem = (GridCommandItem)e.Item;
if (commandItem.NamingContainer is GridTHead)
{
switch (e.Item.OwnerTableView.Name)
{
case "Master":
{
e.Item.OwnerTableView.NoMasterRecordsText = "No record";
break;
}
case "Detail":
{
e.Item.OwnerTableView.NoDetailRecordsText = "No record";
break;
}
}
}
}
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
Below is the table structure from which the grid is binded.
CREATE TABLE [dbo].[Employee](
[Id] [int] IDENTITY(1,1) NOT NULL,
[EmployeeName] [nvarchar](200) NOT NULL,
[IsActive] [bit] NOT NULL
)
Now we will Perform the validation during the insert and the update mode.
First we will see how to show the mandatory field controls Header with Red color.
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
//for showing mandatory fields in red during edit mode
GridEditableItem item = e.Item as GridEditableItem;
((item["EmployeeName"].Parent.Controls[0]) as TableCell).ForeColor = System.Drawing.Color.Red;
}
And Now we will see How to perform validation. We will add the javascript to the update and insert buttons
of the radgrid.
protected void rgdEmployee_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
//for showing mandatory fields in red during edit mode
GridEditableItem item = e.Item as GridEditableItem;
GridEditFormItem editItem = (GridEditFormItem)e.Item;
((item["EmployeeName"].Parent.Controls[0]) as TableCell).ForeColor = System.Drawing.Color.Red;
LinkButton updateBtn = (LinkButton)editItem.FindControl("UpdateButton");
LinkButton cancelBtn = (LinkButton)editItem.FindControl("CancelButton");
TextBox t1 = (TextBox)editItem["EmployeeName"].Controls[0];
if (updateBtn != null)
{
updateBtn.ToolTip = "Update";
cancelBtn.ToolTip = "Cancel";
updateBtn.Attributes.Add("OnClick", "return ValidateEmployee('" + t1.ClientID + "');");
}
LinkButton insertBtn = (LinkButton)editItem.FindControl("PerformInsertButton");
if (insertBtn != null)
{
insertBtn.ToolTip = "Insert";
cancelBtn.ToolTip = "Cancel";
insertBtn.Attributes.Add("OnClick", "return ValidateEmployee('" + t1.ClientID + "');");
}
}
}
and the javascript will be like:
<script type="text/javascript">
function ValidateEmployee(id) {
debugger;
var txtemployee = document.getElementById(id);
if (txtemployee.value == "") {
alert("Please Insert Employee Name");
txtemployee.focus();
return false;
}
}
</script>
Adding controls to a RadGrid template is easy enough, but sometimes we have to interact with them on the client, so that we save a roundtrip to the server. This project demonstrates how to get a reference to the DOM element of a server-side control on the client. The page has two client-side features: single select in a checkbox column; and selecting an item in a dropdown.Example code snppet as below