How to check if Grid Item exists in second Grid

4 posts, 1 answers
  1. bslaght
    bslaght avatar
    184 posts
    Member since:
    Jun 2006

    Posted 30 Oct 2009 Link to this post

    I have two RadGrids (RadGrid1 and RadGrid2)

    In radgrid1 I have a list of jobs with a field called "JobID", on a button click, it inserts JobID and current username into another table which RadGrid2 is based on.

    I would like to add a test/check to my button click event, that checks RadGrid2 to see if the JobID that is being inserted already exist in radgrid2, and if so pop-up a radalert saying that tells the user they already have that JobID in radgrid2.

    I will inclide my current working code, so you can see where I am at, thnks for any help you can provide.
    <%@ Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" 
        CodeFile="view.aspx.vb" Inherits="jobs_view" %> 
     
    <%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %> 
    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">  
    </asp:Content> 
    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">  
        <span class="hdrtext">Available Jobs</span> 
        <telerik:RadGrid ID="RadGrid1" runat="server" DataSourceID="dsViewJobs" GridLines="None" 
            Skin="Default">  
            <MasterTableView AutoGenerateColumns="False" DataKeyNames="JobID" DataSourceID="dsViewJobs">  
                <RowIndicatorColumn> 
                    <HeaderStyle Width="20px"></HeaderStyle> 
                </RowIndicatorColumn> 
                <ExpandCollapseColumn> 
                    <HeaderStyle Width="20px"></HeaderStyle> 
                </ExpandCollapseColumn> 
                <Columns> 
                    <telerik:GridBoundColumn DataField="JobID" DataType="System.Int32" HeaderText="JobID" 
                        ReadOnly="True" SortExpression="JobID" UniqueName="JobID" Visible="False">  
                    </telerik:GridBoundColumn> 
                    <telerik:GridBoundColumn DataField="JobTitle" HeaderText="JobTitle" SortExpression="JobTitle" 
                        UniqueName="JobTitle" Visible="False">  
                    </telerik:GridBoundColumn> 
                    <telerik:GridBoundColumn DataField="JobFile" HeaderText="JobFile" SortExpression="JobFile" 
                        UniqueName="JobFile" Visible="False">  
                    </telerik:GridBoundColumn> 
                    <telerik:GridBoundColumn DataField="PositionQty" DataType="System.Int32" HeaderText="PositionQty" 
                        SortExpression="PositionQty" UniqueName="PositionQty" Visible="False">  
                    </telerik:GridBoundColumn> 
                    <telerik:GridHyperLinkColumn DataNavigateUrlFields="JobFile" DataTextField="JobTitle" 
                        HeaderText="Job Title" UniqueName="JobFileHyperLink">  
                    </telerik:GridHyperLinkColumn> 
                    <telerik:GridTemplateColumn HeaderText="Apply" UniqueName="Apply">  
                        <ItemTemplate> 
                            <asp:Button ID="btnApply" runat="server" Text="Apply" OnClick="btnApply_Click" /> 
                        </ItemTemplate> 
                    </telerik:GridTemplateColumn> 
                </Columns> 
            </MasterTableView> 
        </telerik:RadGrid> 
        <asp:SqlDataSource ID="dsViewJobs" runat="server" ConnectionString="<%$ ConnectionStrings:csSSEA %>" 
            SelectCommand="SELECT * FROM [Jobs] ORDER BY [JobTitle], [PositionQty]" ConflictDetection="CompareAllValues" 
            DeleteCommand="DELETE FROM [Jobs] WHERE [JobID] = @original_JobID AND (([JobTitle] = @original_JobTitle) OR ([JobTitle] IS NULL AND @original_JobTitle IS NULL)) AND (([JobFile] = @original_JobFile) OR ([JobFile] IS NULL AND @original_JobFile IS NULL)) AND [PositionQty] = @original_PositionQty" 
            InsertCommand="INSERT INTO [UserJobs] ([Username], [JobID]) VALUES (@Username, @JobID)" 
            OldValuesParameterFormatString="original_{0}" UpdateCommand="UPDATE [Jobs] SET [JobTitle] = @JobTitle, [JobFile] = @JobFile, [PositionQty] = @PositionQty WHERE [JobID] = @original_JobID AND (([JobTitle] = @original_JobTitle) OR ([JobTitle] IS NULL AND @original_JobTitle IS NULL)) AND (([JobFile] = @original_JobFile) OR ([JobFile] IS NULL AND @original_JobFile IS NULL)) AND [PositionQty] = @original_PositionQty">  
            <DeleteParameters> 
                <asp:Parameter Name="original_JobID" Type="Int32" /> 
                <asp:Parameter Name="original_JobTitle" Type="String" /> 
                <asp:Parameter Name="original_JobFile" Type="String" /> 
                <asp:Parameter Name="original_PositionQty" Type="Int32" /> 
            </DeleteParameters> 
            <UpdateParameters> 
                <asp:Parameter Name="JobTitle" Type="String" /> 
                <asp:Parameter Name="JobFile" Type="String" /> 
                <asp:Parameter Name="PositionQty" Type="Int32" /> 
                <asp:Parameter Name="original_JobID" Type="Int32" /> 
                <asp:Parameter Name="original_JobTitle" Type="String" /> 
                <asp:Parameter Name="original_JobFile" Type="String" /> 
                <asp:Parameter Name="original_PositionQty" Type="Int32" /> 
            </UpdateParameters> 
            <InsertParameters> 
                <asp:ProfileParameter Name="Username" PropertyName="UserName" Type="String" /> 
                <asp:Parameter Name="JobID" DefaultValue="1" Type="Int32" /> 
            </InsertParameters> 
        </asp:SqlDataSource> 
        <br /> 
        <telerik:RadWindowManager ID="RadWindowManager1" runat="server" IconUrl="/img/icons/error.png" 
                    Skin="Forest" Title="Error">  
                    <Windows> 
                    <telerik:RadWindow ID="radconfirm" IconUrl="/img/icons/help.png"></telerik:RadWindow>   
                    </Windows> 
        </telerik:RadWindowManager> 
        <span class="hdrtext">Jobs You Have Applied For</span> 
     
        <script type="text/javascript">  
            var oldConfirm = radconfirm;  
     
            window.radconfirm = function(text, mozEvent) {  
                var ev = mozEvent ? mozEvent : window.event; //Moz support requires passing the event argument manually        
                //Cancel the event        
                ev.cancelBubble = true;  
                ev.returnValue = false;  
                if (ev.stopPropagation) ev.stopPropagation();  
                if (ev.preventDefault) ev.preventDefault();  
     
                //Determine who is the caller        
                var callerObj = ev.srcElement ? ev.srcElement : ev.target;  
     
                //Call the original radconfirm and pass it all necessary parameters        
                if (callerObj) {  
                    //Show the confirm, then when it is closing, if returned value was true, automatically call the caller's click method again.        
                    var callBackFn = function(arg) {  
                        if (arg) {  
                            callerObj["onclick"] = "";  
                            if (callerObj.click) callerObj.click(); //Works fine every time in IE, but does not work for links in Moz        
                            else if (callerObj.tagName == "A") //We assume it is a link button!        
                            {  
                                try {  
                                    eval(callerObj.href)  
                                }  
                                catch (e) { }  
                            }  
                        }  
                    }  
                    oldConfirm('Are you sure you want to delete this job from your application?', callBackFn, 300, 100, null,'Delete Confirmation');  
                }  
                return false;  
            }       
        
        </script> 
     
        <telerik:RadGrid ID="RadGrid2" runat="server" DataSourceID="dsViewJobsAppliedFor" 
            GridLines="None" Skin="Default">  
            <MasterTableView AutoGenerateColumns="False" DataKeyNames="UserJobID" DataSourceID="dsViewJobsAppliedFor" 
                AllowAutomaticDeletes="True">  
                <RowIndicatorColumn> 
                    <HeaderStyle Width="20px"></HeaderStyle> 
                </RowIndicatorColumn> 
                <ExpandCollapseColumn> 
                    <HeaderStyle Width="20px"></HeaderStyle> 
                </ExpandCollapseColumn> 
                <Columns> 
                    <telerik:GridBoundColumn DataField="username" HeaderText="username" SortExpression="username" 
                        UniqueName="username" Visible="False">  
                    </telerik:GridBoundColumn> 
                    <telerik:GridBoundColumn DataField="UserJobID" DataType="System.Int32" HeaderText="UserJobID" 
                        SortExpression="UserJobID" UniqueName="UserJobID" ReadOnly="True" Visible="False">  
                    </telerik:GridBoundColumn> 
                    <telerik:GridBoundColumn DataField="JobID" DataType="System.Int32" HeaderText="JobID" 
                        SortExpression="JobID" UniqueName="JobID" Visible="False">  
                    </telerik:GridBoundColumn> 
                    <telerik:GridBoundColumn DataField="JobTitle" HeaderText="JobTitle" SortExpression="JobTitle" 
                        UniqueName="JobTitle" Visible="False">  
                    </telerik:GridBoundColumn> 
                    <telerik:GridBoundColumn DataField="JobFile" HeaderText="JobFile" SortExpression="JobFile" 
                        UniqueName="JobFile" Visible="False">  
                    </telerik:GridBoundColumn> 
                    <telerik:GridHyperLinkColumn DataNavigateUrlFields="JobFile" DataTextField="JobTitle" 
                        HeaderText="Job Title" UniqueName="column">  
                    </telerik:GridHyperLinkColumn> 
                    <%--<telerik:GridButtonColumn ButtonType="PushButton" CommandName="Delete"   
                Text="Delete" UniqueName="Delete" HeaderText="Delete"   
                ConfirmText="Are you sure you want to delete this job from your application?" > 
            </telerik:GridButtonColumn>--%> 
                    <telerik:GridTemplateColumn UniqueName="DeleteColumn" HeaderText="Delete">  
                        <%-- <HeaderTemplate>    
                                    <table width="100%">     
                                        <tr>    
                                            <td style="width:50%">     
                                                RadConfirm</td>    
                                            <td style="width:50%">     
                                                Default confirm</td>    
                                        </tr>    
                                    </table>    
                                </HeaderTemplate>--%> 
                        <ItemTemplate> 
                            <asp:Button ID="btnDelete" ToolTip="Delete Record" runat="server" CausesValidation="False" 
                                Text="Delete" CommandName="Delete" OnClientClick="return radconfirm('Are you sure you want to delete this record?', event);" /> 
                            <%--<table width="100%">     
                                        <tr>    
                                            <td>    
                                                </td>     
                                            <td>    
                                                <asp:ImageButton ID="ImageButton1" ToolTip="Delete Record" runat="server" CausesValidation="False"    
                                                    CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?');"    
                                                    ImageUrl="~/RadControls/Grid/Skins/Default/Delete.gif" />    
                                            </td>    
                                        </tr>    
                                    </table>--%> 
                        </ItemTemplate> 
                    </telerik:GridTemplateColumn> 
                </Columns> 
                <EditFormSettings> 
                    <EditColumn ButtonType="ImageButton">  
                    </EditColumn> 
                </EditFormSettings> 
            </MasterTableView> 
        </telerik:RadGrid> 
        <asp:SqlDataSource ID="dsViewJobsAppliedFor" runat="server" ConflictDetection="CompareAllValues" 
            ConnectionString="<%$ ConnectionStrings:csSSEA %>" DeleteCommand="DELETE FROM [UserJobs] WHERE [userjobid] = @original_userjobid" 
            InsertCommand="INSERT INTO [UserJobs] ([Username], [JobID]) VALUES (@Username, @JobID)" 
            OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT uj.username, uj.UserJobID, uj.JobID, j.JobTitle, j.JobFile FROM UserJobs uj, Jobs j WHERE ([Username] = @UserName) and uj.jobid = j.jobid" 
            UpdateCommand="UPDATE [UserJobs] SET [Username] = @Username, [JobID] = @JobID WHERE [id] = @original_id AND [Username] = @original_Username AND [JobID] = @original_JobID">  
            <SelectParameters> 
                <asp:ProfileParameter Name="Username" PropertyName="UserName" Type="String" /> 
            </SelectParameters> 
            <DeleteParameters> 
                <asp:Parameter Name="original_userjobid" Type="Int32" /> 
                <asp:Parameter Name="original_Username" Type="String" /> 
                <asp:Parameter Name="original_JobID" Type="Int32" /> 
            </DeleteParameters> 
            <UpdateParameters> 
                <asp:Parameter Name="Username" Type="String" /> 
                <asp:Parameter Name="JobID" Type="Int32" /> 
                <asp:Parameter Name="original_id" Type="Int32" /> 
                <asp:Parameter Name="original_Username" Type="String" /> 
                <asp:Parameter Name="original_JobID" Type="Int32" /> 
            </UpdateParameters> 
            <InsertParameters> 
                <asp:Parameter Name="Username" Type="String" /> 
                <asp:Parameter Name="JobID" Type="Int32" /> 
            </InsertParameters> 
        </asp:SqlDataSource> 
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">  
            <AjaxSettings> 
                <telerik:AjaxSetting AjaxControlID="RadGrid1">  
                    <UpdatedControls> 
                        <telerik:AjaxUpdatedControl ControlID="RadGrid2" /> 
                        <telerik:AjaxUpdatedControl ControlID="RadWindowManager1" /> 
                    </UpdatedControls> 
                </telerik:AjaxSetting> 
            </AjaxSettings> 
        </telerik:RadAjaxManager> 
    </asp:Content> 
     

    Imports Telerik.Web.UI  
    Imports System.Configuration  
    Imports System.Data.SqlClient  
    Imports System.Data  
    Imports ProfileCommon  
     
    Partial Class jobs_view  
        Inherits System.Web.UI.Page  
        Protected Sub btnApply_Click(ByVal sender As ObjectByVal e As System.EventArgs)  
     
            Dim rowCount As Integer = RadGrid2.MasterTableView.GetItems(New GridItemType() {GridItemType.Item, GridItemType.AlternatingItem}).Length  
            If rowCount >= 5 Then 
     
                RadAjaxManager1.ResponseScripts.Add("radalert('Sorry, you can only apply for five (5) jobs.  Please remove a job from your list and try agian.', 330, 210);")  
     
            Else 
     
     
                'Configure SQL Connection  
                Dim cn As SqlConnection = New SqlConnection  
                Dim cmd As SqlCommand = New SqlCommand  
                Dim connString As String = ConfigurationManager.ConnectionStrings("csSSEA").ConnectionString  
                cn.ConnectionString = connString  
                cmd.CommandText = "[usp_UserJobsInsert]" 
                cmd.CommandType = System.Data.CommandType.StoredProcedure  
                cmd.Connection = cn  
     
                'Gets the name if authenticated.  
                Dim CurrentUserName As String 
                If User.Identity.IsAuthenticated Then 
                    CurrentUserName = User.Identity.Name  
                Else 
                    CurrentUserName = "N/A" 
                End If 
     
                'Get Datagrid Values and declare as sql param      
                Dim btn As Button = DirectCast(sender, Button)  
                Dim dataItem As GridDataItem = DirectCast(btn.NamingContainer, GridDataItem)  
                Dim strJobID As String = dataItem("JobID").Text  
                Dim dataItemKeys As Telerik.Web.UI.GridDataItem = DirectCast(btn.NamingContainer, Telerik.Web.UI.GridDataItem)  
                Dim JobID As String = dataItemKeys("JobId").Text  
     
                cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = CurrentUserName  
                cmd.Parameters.Add("@JobID", SqlDbType.Int).Value = JobID  
     
                Try 
                    If cn.State = ConnectionState.Closed Then 
                        cn.Open()  
                    End If 
                    cmd.ExecuteNonQuery()  
                    cn.Close()  
                    cn.Dispose()  
                Catch ex As Exception  
                End Try 
                RadGrid2.Rebind()  
            End If 
        End Sub 
     
     
    End Class 
     

  2. Answer
    Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 02 Nov 2009 Link to this post

    Hi,

    A suggetsion would be to loop through the items of the RadGrid2 and check if the corresponding  job id matches the  job id  you are about to insert .

    C#:
    public void btnApply_Click(object as s ender , System.EventArgs e ) 
     foreach (GridDataItem dataItem in RadGrid1.MasterTableView.Items)   
            {   
                 if(dataItem["JobID"]==JobID) 
                     Response.Write("Record already exists")  
            } 
     


    Thanks,
    Shinu
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. bslaght
    bslaght avatar
    184 posts
    Member since:
    Jun 2006

    Posted 02 Nov 2009 Link to this post

    Hi Shinu.
     I modified your code to work in VB. and have pasted it below.  However I don't see how this compares the items between the two grids.  As soon as I apply for any job, all other jobs come back with "Sorry you have already appled for this job", when I haven't.

    How do I chnage this code to compare the JobID between the two grids? (RadGrid1 and RadGrid2)

    Protected Sub btnApply_Click(ByVal sender As ObjectByVal e As System.EventArgs)  
     
            'Check to see if the applicant has already applied for this job  
            For Each item As GridDataItem In RadGrid1.MasterTableView.Items  
                Dim btnApply As Button = DirectCast(sender, Button)  
                Dim di As GridDataItem = DirectCast(btnApply.NamingContainer, GridDataItem)  
                Dim currJobID As String = di("JobID").Text  
                Dim diKeys As Telerik.Web.UI.GridDataItem = DirectCast(btnApply.NamingContainer, Telerik.Web.UI.GridDataItem)  
                Dim varJobID As String = diKeys("JobId").Text  
     
                If currJobID = varJobID Then 
                    RadAjaxManager1.ResponseScripts.Add("radalert('Sorry, you have already applied for this job.', 330, 210);")  
                    GoTo EXIT_SUB  
                End If 
     
            Next 
  5. bslaght
    bslaght avatar
    184 posts
    Member since:
    Jun 2006

    Posted 02 Nov 2009 Link to this post

    After some fiddling I was ableto work out the kinks and have got my test working with the code below.
     'Check to see if the applicant has already applied for this job  
            For Each item As GridDataItem In RadGrid2.MasterTableView.Items  
               
                Dim curJobID As String = item("JobID").Text.ToString()  
     
                Dim btnApply As Button = DirectCast(sender, Button)  
                Dim di As GridDataItem = DirectCast(btnApply.NamingContainer, GridDataItem)  
                Dim currJobID As String = di("JobID").Text  
                Dim diKeys As GridDataItem = DirectCast(btnApply.NamingContainer, GridDataItem)  
                Dim varJobID As String = diKeys("JobId").Text  
     
     
                If curJobID = varJobID Then 
                    RadAjaxManager1.ResponseScripts.Add("radalert('Sorry, you have already applied for this job.', 330, 210);")  
                    GoTo EXIT_SUB  
                End If 
     
            Next 

    However, I now have an issue where my delete button will only work if it is the first button pushed after the page loads and it will only work once.  I will open a new thred for this.

    Brett
Back to Top