简体   繁体   中英

How and Where do i enter the code to edit just one column of a datagridview

替代文字

Okay so i have created the datagridview all right and enabled editing to the column as seen in the picture below. next i want to write a click event for the edit link such that when it is clicked, only the investigatorID column is available for editing. At that instance when changes can be made, i want the investigator column to display a dropdownlist of investigators that can be selected and that selected item be bound to the row on which the edit link was clicked.

I have the datasource to display the investigatorIDs am only wondering where to write the code for the click even of the edit link and have it do the magic.

Lets work some Magic people..:) Then i thought again and a better idea came up since i only need the investigator id to be passed into the database to be updated, i edited the design as follows(see picture below) so instead of having the exhibit type and image displayed in the grid view, i rather call up just the exhibit id to which the investigatorID will be assigned it makes more sense when you have a look at the database below:

though not fully populated but the concept behind the database is that:1. one case may be linked to more than one exhibit (so to say one case has many exhibits and each of those exhibits is assigned an investigating officer that cannot be working on more than 3 exhibits at a time.

so at this stage when investigators are assigned to a case, the caseID,and Exhibit details , are already populated. the Admin that opened the case would already have their ID there and the manager that is yet to assign the case would have their id and the investigators ID to be assigned to the fields.

Looking at my second design i have been able to create a grid to display only investigators that are working on a 2 or less exhibits. which means they are available to be assigned on at least one more exhibit. so to do the assigning, i select a CaseID from the dropdown list which details all cases from the case table(not shown here) and based on the selected case, i display all exhibitID linked to the selected casedID. from there, the user can select one Exhibit from the dropdownlist and and then select any of the available investigators to assign. so all i need to do now is when the user clicks the assign button, i want to know where and how i can make the investigatorsID against which the assign button was clicked be passed into the exhibits table as an update and that gridvire (userID, Username aka investigators list) be refereshed so that should the investigatorID that was recently clicked reached its threshold of three exhibits, their investigatorsID and name does not show up. and at the same time, the exhibit that has already been assigned also does not show up again in the dropdownlist. So in effect, the assign button is clicked, and the ID next to thatis sent to the exhibit table for update and the gridview together with the exhibit dropdownlist is refreshed.

there shouldnt be a problem with the grid view since its datais directly binded so a simple exhibitgridview.databind() should work it out and pobably calling the method that previously populated the exhibitdropdownlist would work the refresh for the dropdownlist as well...

so the problem here now is how to get the codes behind assign button click for this events to take place. please find attached below the code behind for the masterpages (using a nested masterpage) and the code behind and .cs file for the current page where this is supposed to happen.

First master page (SITE.MASTER) Code behind

    <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="Prototype5.SiteMaster" %>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript">
//            $(function () {
//                $("#showOpenCasePage").click(function () {
//                    $("#CaseMainPanel").load("/EntryForms/OpenCase.aspx");
//                });
//                $("#showAddExhibitPage").click(function () {
//                    $("#CaseMainPanel").load("/EntryForms/AddExhibit.aspx");
//                });
//                $("#showOpenCasePage").click(function () {
//                    $("#CaseManagementMainPanel").load("/EntryForms/OpenCase.aspx");
//                });
//                $("#showAddExhibitPage").click(function () {
//                    $("#CaseManagementMainPanel").load("/EntryForms/AddExhibit.aspx");
//                });
//                $("#showAllocateOfficerPage").click(function () {
//                    $("#CaseManagementMainPanel").load("/EntryForms/AllocateOfficer.aspx");
//                });

//                $("#showReallocateOfficerPage").click(function () {
//                    $("#CaseManagementMainPanel").load("/EntryForms/ReallocateOfficer.aspx");
//                });

//                $("#showPrioritizeCasePage").click(function () {
//                    $("#CaseManagementMainPanel").load("/EntryForms/CasePriority.aspx");
//                });
//                $("#showRecordFindingPage").click(function () {
//                    $("#InvestigatorMainPanel").load("/EntryForms/RecordFinding.aspx");
//                });
//                $("#showUpdateStatusPage").click(function () {
//                    $("#InvestigatorMainPanel").load("/EntryForms/UpdateStatus.aspx");
//                });
//            });


        </script>

    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
    <script type="text/javascript">


        function updateClock() {
            var currentTime = new Date();

            var currentHours = currentTime.getHours();
            var currentMinutes = currentTime.getMinutes();
            var currentSeconds = currentTime.getSeconds();

            // Pad the minutes and seconds with leading zeros, if required
            currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
            currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;

            // Choose either "AM" or "PM" as appropriate
            var timeOfDay = (currentHours < 12) ? "AM" : "PM";

            // Convert the hours component to 12-hour format if needed
            currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;

            // Convert an hours component of "0" to "12"
            currentHours = (currentHours == 0) ? 12 : currentHours;

            // Compose the string for display
            var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;

            // Update the time display
            document.getElementById("clock").firstChild.nodeValue = currentTimeString;
        }


</script>
        <style type="text/css">
            .style1
            {
                width: 213px;
            }
            .menu
            {}
            .style2
            {
                width: 100%;
            }
            .style3
            {
                width: 264px;
            }
            .style4
            {
                width: 291px;
            }
        </style>
</head>
<body onload="updateClock(); setInterval('updateClock()', 1000 )">
    <form id="Form1" runat="server">
    <div class="page">
        <div class="header">
            <div class="title">
                <span style="font-size: 5em; font-family:Old English Text MT; color: #FF6600;"><strong>Case Management System</strong></span>
            </div>
            <div class="clock">
                <span id="clock">&nbsp;</span>
            </div>
            <div class="clear hideSkiplink">
                <table class="style2">
                    <tr>
                        <td class="style4" align="center">
                    <asp:LoginView ID="MasterLoginView" runat="server">
                        <LoggedInTemplate>
                            Welcome <span class="bold"><asp:LoginName ID="HeadLoginName" runat="server" /> 

                        [ <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" LogoutPageUrl="~/Logout.aspx"/> ]
                            <%--Welcome: 
                            <span class="bold"><asp:LoginName ID="MasterLoginName" runat="server" /> </span>!--%>                       
                        </LoggedInTemplate>
                        <AnonymousTemplate>
                            Welcome: Guest
                            [ <a href="Account/Login.aspx" ID="HeadLoginStatus" runat="server">Log In</a> ]
                        </AnonymousTemplate>

                    </asp:LoginView>
                        </td>
                        <td class="style3">
                            &nbsp;</td>
                        <td valign="top">
                <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="False" 
                                IncludeStyleBlock="False" Orientation="Horizontal" Height="36px" Width="120px">
                    <Items>
                        <asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home" 
                            ImageUrl="~/Images/homeIcon.png"/>
                        <asp:MenuItem NavigateUrl="~/About.aspx" Text="About" 
                            ImageUrl="~/Images/aboutIcon.png"/>
                        <asp:MenuItem ImageUrl="~/Images/contactUsIcon.png" NavigateUrl="~/ContactUs.aspx" 
                            Text="Contact Us" Value="Contact Us"></asp:MenuItem>
                    </Items>
                </asp:Menu>
                        </td>
                    </tr>
                </table>
            </div>
                </div>

                </div>

                <div class="page" style="margin-top:5px;height:auto;">


                            <div style="border-style:solid;">
                                <table style="width:100%; background-color:#3a4f63">
                                    <tr>
                                        <td class="style1" valign="top">
                                                   <p style="padding-left: 4px; padding-right:4px;">
                                            <asp:Button ID="functionButton" runat="server" Text="System Functions" 
                                                    class="fnctButton" Height="41px" Width="192px" />

                                            <asp:ContentPlaceHolder ID="LeftNavigation" runat="server">            


                                            </asp:ContentPlaceHolder>
                                            </p>
                                        </td>

                                        <td rowspan="2" valign="top" align="center">
                                                <asp:ContentPlaceHolder ID="MainContent" runat="server"/>
                                        </td>
                                    </tr>

                                        <tr>
                                            <td class="style1" align="left" valign="top">

                                                    <asp:ContentPlaceHolder ID="RightNewsItem" runat="server"/>           


                                            </td>
                                        </tr>
                            </table>                 

                            </div>

                </div>



        <div class="clear">
        </div>

        <div class="footer">

            <span style="font-size: small;color: #FFFFFF;"><strong>Copyright 2011 JustRite Software Inc.</strong></span></div>
    </form>
</body>
</html>

Second Master page based on the first one (Manage.Master)

   <%@ Master Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Manager.master.cs" Inherits="Prototype5.Manager" %>
<asp:Content ID="ManagerHead" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="ManagerLeft" ContentPlaceHolderID="LeftNavigation" runat="server">

    <div style="margin-top:20px; margin-bottom:20px;">    
            <p class="actionButton">
                <asp:Button ID="allocateInvestigatorsButton" runat="server" 
                    Text="Allocate Investigators" height="30px" width="135px" 
                    onclick="allocateInvestigatorsButton_Click" />
                 </p>
            <p class="actionButton">
                <asp:Button ID="realocateInvestigatorsButton" runat="server" 
                    Text="Reallocate Investigators" Height="30px" Width="135px" 
                    onclick="realocateInvestigatorsButton_Click" />
                 </p>
            <p class="actionButton">
                <asp:Button ID="prioritizeCaseButton" runat="server" 
                    Text="Prioritize Case" height="30px" width="135px" 
                    onclick="prioritizeCaseButton_Click" />
                 </p>
            <p class="actionButton">
                <asp:Button ID="openCaseButton" runat="server" 
                    Text="Open Case" height="30px" width="135px" 
                    onclick="openCaseButton_Click" />
            </p>
            <p class="actionButton">
                <asp:Button ID="registerExhibitButton" runat="server" 
                    Text="Register Exhibit" height="30px" width="135px" 
                    onclick="registerExhibitButton_Click" />
                </p>
    </div>
</asp:Content>


<asp:Content ID="ManagerMain" ContentPlaceHolderID="MainContent" runat="server">
    <asp:ContentPlaceHolder ID="MainContent" runat="server"/>
</asp:Content>
<asp:Content ID="ManagerRight" ContentPlaceHolderID="RightNewsItem" runat="server">
    <asp:Button ID="AlertButton" runat="server" Text="Alerts" 
                            class="fnctButton" Height="25px" Width="70px" />

    <div style="border-style: none; border-color: inherit; border-width: medium; width:210px; height: 103px;"> 
                    <p style="text-align: justify; font-size:1.2em; color:White; width: 209px; height: 95px;">
                        This is a place holder for allerts about cases to which the investigator has been assigned to.
                    </p>
                    </div>
</asp:Content>

Current Page containing elements based on second master page based on second master page

    <%@ Page Title="" Language="C#" MasterPageFile="~/Manager.master" AutoEventWireup="true" CodeBehind="AllocateInvestigators.aspx.cs" Inherits="Prototype5.AllocateInvestigators" %>
<asp:Content ID="AllocateInvestigatorsMain" ContentPlaceHolderID="MainContent" runat="server">

    <div>
    <table class="style2">
        <tr>
            <td colspan="4" style="background-color: #C0C0C0">
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style1" 
                style="width: 79px; color: #000000; background-color: #666666;">
                <strong>Case ID:</strong></td>
            <td  align="left" class="style1" style="width: 187px">
                <asp:DropDownList ID="caseIDDropDownList" runat="server" Height="22px" 
                    Width="116px" DataSourceID="distinctCaseIDSqlDataSource" 
                    DataTextField="CaseID" DataValueField="CaseID" 
                    onselectedindexchanged="caseIDDropDownList_SelectedIndexChanged">
                </asp:DropDownList>
                <asp:SqlDataSource ID="distinctCaseIDSqlDataSource" runat="server" 
                    ConnectionString="<%$ ConnectionStrings:CMSSQL3ConnectionString1 %>" SelectCommand="SELECT DISTINCT CaseID FROM Exhibits
    WHERE InvestigatorID = NULL"></asp:SqlDataSource>
            </td>
            <td class="style3" 
                style="width: 119px; color: #000000; background-color: #666666;">
                <strong>Case Priority:</strong></td>
            <td align="left">
                <asp:DropDownList ID="casePriorityDropDownList" runat="server" height="22px" 
                    width="116px">
                    <asp:ListItem>Low</asp:ListItem>
                    <asp:ListItem>Medium</asp:ListItem>
                    <asp:ListItem>High</asp:ListItem>
                </asp:DropDownList>
            </td>
        </tr>
        <tr>
            <td colspan="4" style="background-color: #C0C0C0">
                &nbsp;</td>
        </tr>
    </table>
</div>
<div>

    <table class="style2">
        <tr>
            <td style="width: 79px; color: #000000;">
                <strong>Exhibit ID:</strong></td>
            <td align="left">
                <asp:DropDownList ID="exhibitsDropDownList" runat="server" height="22px" 
                    onselectedindexchanged="exhibitsDropDownList_SelectedIndexChanged" 
                    width="116px">
                </asp:DropDownList>
                <asp:SqlDataSource ID="exhibitIDSqlDataSource" runat="server" 
                    ConnectionString="<%$ ConnectionStrings:CMSSQL3ConnectionString1 %>" 
                    SelectCommand="SELECT ExhibitID FROM Exhibits"></asp:SqlDataSource>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                &nbsp;</td>
        </tr>
    </table>

</div>
<div>
    <table class="style2">
        <tr>
            <td>
                <asp:GridView ID="exhibitGridView" runat="server" AutoGenerateColumns="False" 
                    CellPadding="4" DataKeyNames="UserID" DataSourceID="SqlDataSource1" 
                    EmptyDataText="There are no data records to display." ForeColor="#333333" 
                    GridLines="None" Height="241px" 
                    onselectedindexchanged="GridView1_SelectedIndexChanged" Width="323px" 
                    style="margin-right: 0px">
                    <AlternatingRowStyle BackColor="White" />
                    <Columns>
                        <asp:BoundField DataField="UserID" HeaderText="UserID" ReadOnly="True" 
                            SortExpression="UserID" />
                        <asp:BoundField DataField="UserName" HeaderText="UserName" 
                            SortExpression="UserName" />
                        <asp:ButtonField ButtonType="Button" CommandName="Select" Text="Assign" />
                    </Columns>
                    <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
                    <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
                    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
                    <SortedAscendingCellStyle BackColor="#FDF5AC" />
                    <SortedAscendingHeaderStyle BackColor="#4D0000" />
                    <SortedDescendingCellStyle BackColor="#FCF6C0" />
                    <SortedDescendingHeaderStyle BackColor="#820000" />
                </asp:GridView>
                <asp:SqlDataSource ID="assignInvestigatorsSqlDataSource" runat="server" 
                    ConnectionString="<%$ ConnectionStrings:CMSSQL3ConnectionString1 %>" 
                    SelectCommand="SELECT ExhibitID, ExhibitType, ExhibitImage, InvestigatorID FROM Exhibits">
                </asp:SqlDataSource>
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                    ConnectionString="<%$ ConnectionStrings:CMSSQL3ConnectionString1 %>" 
                    DeleteCommand="DELETE FROM [Exhibits] WHERE [ExhibitID] = @ExhibitID AND [CaseID] = @CaseID" 
                    InsertCommand="INSERT INTO [Exhibits] ([CaseID], [ExhibitType], [DateReceived], [StoredLocation], [OfficerID], [SuspectID], [InvestigatorID], [ManagerID], [AdminID]) VALUES (@CaseID, @ExhibitType, @DateReceived, @StoredLocation, @OfficerID, @SuspectID, @InvestigatorID, @ManagerID, @AdminID)" 
                    ProviderName="<%$ ConnectionStrings:CMSSQL3ConnectionString1.ProviderName %>" 
                    SelectCommand="SELECT UserID, UserName
FROM Users
WHERE UserID IN (SELECT UserID
        FROM Users
        WHERE UserType LIKE 'Investigator'
        AND UserID NOT IN (SELECT InvestigatorID 
                From Exhibits 
                GROUP BY (InvestigatorID) 
                HAVING COUNT(InvestigatorID) &gt; 2));" 

                    UpdateCommand="UPDATE [Exhibits] SET [ExhibitType] = @ExhibitType, [DateReceived] = @DateReceived, [StoredLocation] = @StoredLocation, [OfficerID] = @OfficerID, [SuspectID] = @SuspectID, [InvestigatorID] = @InvestigatorID, [ManagerID] = @ManagerID, [AdminID] = @AdminID WHERE [ExhibitID] = @ExhibitID AND [CaseID] = @CaseID">
                    <DeleteParameters>
                        <asp:Parameter Name="ExhibitID" Type="Int32" />
                        <asp:Parameter Name="CaseID" Type="Int32" />
                    </DeleteParameters>
                    <InsertParameters>
                        <asp:Parameter Name="CaseID" Type="Int32" />
                        <asp:Parameter Name="ExhibitType" Type="String" />
                        <asp:Parameter Name="DateReceived" Type="DateTime" />
                        <asp:Parameter Name="StoredLocation" Type="String" />
                        <asp:Parameter Name="OfficerID" Type="String" />
                        <asp:Parameter Name="SuspectID" Type="Int32" />
                        <asp:Parameter Name="InvestigatorID" Type="String" />
                        <asp:Parameter Name="ManagerID" Type="String" />
                        <asp:Parameter Name="AdminID" Type="String" />
                    </InsertParameters>
                    <UpdateParameters>
                        <asp:Parameter Name="ExhibitType" Type="String" />
                        <asp:Parameter Name="DateReceived" Type="DateTime" />
                        <asp:Parameter Name="StoredLocation" Type="String" />
                        <asp:Parameter Name="OfficerID" Type="String" />
                        <asp:Parameter Name="SuspectID" Type="Int32" />
                        <asp:Parameter Name="InvestigatorID" Type="String" />
                        <asp:Parameter Name="ManagerID" Type="String" />
                        <asp:Parameter Name="AdminID" Type="String" />
                        <asp:Parameter Name="ExhibitID" Type="Int32" />
                        <asp:Parameter Name="CaseID" Type="Int32" />
                    </UpdateParameters>
                </asp:SqlDataSource>
            </td>
        </tr>
    </table>
</div>
<div>
    <table class="style2">
        <tr>
            <td>
                &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
    </table>
</div>
</asp:Content>

AND lastly the .cs file of the current page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace Prototype5
{
    public partial class AllocateInvestigators : System.Web.UI.Page
    {
        SqlConnection caseConnection = new SqlConnection();
        SqlConnection exhibitConnection = new SqlConnection();
        DataSet caseDataSet = new DataSet();
        DataSet exhibitDataSet = new DataSet();
        SqlDataAdapter caseSqlDataAdapter = new SqlDataAdapter();
        SqlDataAdapter exhibitSqlDataAdapter = new SqlDataAdapter();
        protected void Page_Load(object sender, EventArgs e)
        {
            //exhibitGridView.Enabled = false;
        }

        protected void caseIDDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            exhibitGridView.Enabled = true;

            string selectedCaseID = caseIDDropDownList.SelectedItem.Text.ToString();
            CreateExhibitDataset();
            DataView exhibitDataView = new DataView(exhibitDataSet.Tables[0]);
            exhibitDataView.RowFilter = "CaseID = '" + selectedCaseID + "' ";
           exhibitsDropDownList.DataSource = exhibitDataView;
           exhibitsDropDownList.DataBind();
        }
        private void CreateDataSet()
        {
            caseConnection.ConnectionString =
           distinctCaseIDSqlDataSource.ConnectionString;
            caseSqlDataAdapter.SelectCommand = new
            SqlCommand(distinctCaseIDSqlDataSource.SelectCommand, caseConnection);
            caseSqlDataAdapter.Fill(caseDataSet);
        }
        private void CreateExhibitDataset()
        {
            exhibitConnection.ConnectionString =
           exhibitIDSqlDataSource.ConnectionString;
            exhibitSqlDataAdapter.SelectCommand = new
            SqlCommand(exhibitIDSqlDataSource.SelectCommand, caseConnection);
            exhibitSqlDataAdapter.Fill(exhibitDataSet);
        }



    }
}

Counting on your kind help...@_@...

替代文字替代文字

Is this what you are looking for?

替代文字

I have used sample NorthWind DB, so you might have to add DataSources to the GridView. Here is the markup

<asp:GridView ID='GridView1' runat="server" AutoGenerateColumns='False'
        DataSourceID='ObjectDataSource1' DataKeyNames='ProductID' 
        AllowPaging='True'>
        <Columns>
            <asp:BoundField HeaderText='Name' DataField='ProductName' ReadOnly='true'/>
            <asp:TemplateField HeaderText='Order'>
                <EditItemTemplate>
                    <asp:DropDownList ID='DropDownList1' runat='server' DataTextField='ProductName' DataValueField='ProductID'>
                        <asp:ListItem Enabled='true' Selected='True' Value='2'>

                        </asp:ListItem>
                        <asp:ListItem Value='1'></asp:ListItem>
                        <asp:ListItem Value='3'></asp:ListItem>
                    </asp:DropDownList>
                </EditItemTemplate>
               <ItemTemplate>
                    <asp:Label ID='Label1' runat="server" Text='<%# Eval("UnitsOnOrder") %>'></asp:Label>
               </ItemTemplate>
            </asp:TemplateField>
            <asp:CommandField ShowEditButton='true'  ButtonType='Link' EditText='Edit' UpdateText='Update' CancelText='Cancel' />
        </Columns>
</asp:GridView>

Also you have to set the DropDownList's datasource too. In the above markup I've hard-coded ListItems.


Update - Handle OnRowUpdating event on GridView

After update link is clicked the GridView fires OnRowUpdating event... In the event handler you might get the values of the controls (in that row) and act on it, like update your data. Below is the code snippet... (you have to add OnRowUpdating='HandleOnGridViewRowUpdating' to gridview's markup)

 protected void HandleOnGridViewRowUpdating(Object sender, GridViewUpdateEventArgs e)
    {
        DropDownList dropDownList = 
            GridView1.Rows[e.RowIndex].FindControl("DropDownList1") as DropDownList;
        //got the selected value of dropdown..
        //get other required values from the GridView1...
        //the DataKeyNames is set to ProductID.. so e.Keys["ProductID"] should give you the   //ProductID..
        //write a sql that takes these values and updates the db...
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM