简体   繁体   English

为什么无法在此 GridView 中更新数据

[英]Why the data cannot be updated in this GridView

I am a new ASP.NET developer and trying to use a GridView control to show all the employees in the employee table in the database.我是一名新的 ASP.NET 开发人员,并尝试使用 GridView 控件来显示数据库中员工表中的所有员工。 I am working now in enabling updating the information in the GridView.我现在正在努力更新 GridView 中的信息。 I am facing the following probelm and I don't know why:我面临以下问题,我不知道为什么:

** **

Updating is not supported by data source 'SqlDataSource1' unless UpdateCommand is specified.除非指定了 UpdateCommand,否则数据源“SqlDataSource1”不支持更新。

** **

FYI, I have the following database design:仅供参考,我有以下数据库设计:

Employee Table: Username, Name, JobTitle, BadgeNo, IsActive, DivisionCode
Divisions Table: SapCode, DivisionShortcut

(IsActive is like a flag (bit datatype) to indicate if the employee is in an assignment or not) (IsActive 就像一个标志(位数据类型),用于指示员工是否在分配中)

ASP.NET code: ASP.NET 代码:

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" 
            AutoGenerateColumns="False" DataKeyNames="Username" 
            DataSourceID="SqlDataSource1" BorderWidth="1px" BackColor="#DEBA84" 
             CellPadding="3" CellSpacing="2" BorderStyle="None" 
             BorderColor="#DEBA84" OnRowEditing="GridView1_RowEditing" 
             OnRowCancelingEdit="GridView1_RowCancelingEdit" 
             OnRowUpdating="GridView1_RowUpdating">
            <FooterStyle ForeColor="#8C4510" 
              BackColor="#F7DFB5"></FooterStyle>
            <PagerStyle ForeColor="#8C4510" 
              HorizontalAlign="Center"></PagerStyle>
            <HeaderStyle ForeColor="White" Font-Bold="True" 
              BackColor="#A55129"></HeaderStyle>
            <Columns>
                <asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true" />

                <asp:TemplateField>
                    <ItemTemplate>
                        <%# Eval("DivisionShortcut")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="DivisionsList" runat="server" DataSourceID="DivisionsListDataSource"
                                            DataTextField="DivisionShortcut" DataValueField="SapCode"></asp:DropDownList>
                    </EditItemTemplate>
                </asp:TemplateField>

                <asp:BoundField DataField="Username" HeaderText="Network ID" ReadOnly="True" 
                    SortExpression="Username" />

                <asp:TemplateField>
                    <ItemTemplate>
                        <%# Eval("Name")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Eval("Name")%>' />
                    </EditItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField>
                    <ItemTemplate>
                        <%# Eval("JobTitle")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtJobTitle" runat="server" Text='<%# Eval("JobTitle")%>' />
                    </EditItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField>
                    <ItemTemplate>
                        <%# Eval("BadgeNo")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtBadgeNo" runat="server" Text='<%# Eval("BadgeNo")%>' />
                    </EditItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField>
                    <ItemTemplate>
                        <%# Eval("IsActive")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:CheckBox ID="isActive" runat="server" Text='<%# Eval("IsActive")%>' />
                    </EditItemTemplate>
                </asp:TemplateField>

            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:UsersInfoDBConnectionString %>" 

            SelectCommand="SELECT     dbo.Divisions.DivisionShortcut, dbo.employee.Username, dbo.employee.Name, dbo.employee.JobTitle, dbo.employee.BadgeNo, dbo.employee.IsActive
FROM         dbo.Divisions INNER JOIN
                      dbo.employee ON dbo.Divisions.SapCode = dbo.employee.DivisionCode">
        </asp:SqlDataSource>

        <asp:SqlDataSource ID="DivisionsListDataSource" runat="server" 
            ConnectionString="<%$ ConnectionStrings:UsersInfoDBConnectionString %>" 
            SelectCommand="SELECT * FROM Divisions">
        </asp:SqlDataSource>

Code-Behind:代码隐藏:

//For updating the information in any row in the GridView
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow gvrow = GridView1.Rows[e.RowIndex];

        DropDownList DivisionsList = (DropDownList)gvrow.FindControl("DivisionsList"); 

        TextBox txtEmployeeName = (TextBox)gvrow.FindControl("txtEmployeeName");
        TextBox txtJobTitle = (TextBox)gvrow.FindControl("txtJobTitle");
        TextBox txtBadgeNo = (TextBox)gvrow.FindControl("txtBadgeNo");

        CheckBox isActive = (CheckBox)gvrow.FindControl("isActive");

        //For getting the ID (primary key) of that row
        string username = GridView1.DataKeys[e.RowIndex].Value.ToString();

        string name = txtEmployeeName.Text;
        string jobTitle = txtJobTitle.Text;
        string badgeNo = txtBadgeNo.Text;

        UpdateEmployeeInfo(username, name, jobTitle, badgeNo);
    }


    private void UpdateEmployeeInfo(string username, string name, string jobTitle, string badgeNo)
    {
        try
        {
            string connString = ConfigurationManager.ConnectionStrings["UsersInfoDBConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(connString);
            string update = @"UPDATE Employee SET Name = @Name, JobTitle = @JobTitle, 
                                                BadgeNo = @BadgeNo 
                            WHERE Username = @Username";
            SqlCommand cmd = new SqlCommand(update, conn);

            cmd.Parameters.AddWithValue("@Name", name);
            cmd.Parameters.AddWithValue("@JobTitle", jobTitle);
            cmd.Parameters.AddWithValue("@BadgeNo", badgeNo);
            cmd.Parameters.AddWithValue("@Username", username);

            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();

            GridView1.EditIndex = -1;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

So could you please help me in modifying this?所以你能帮我修改这个吗?

The SqlDataSource can do the updates in the database directly for you. SqlDataSource可以直接为您在数据库中进行更新。

You don't need to capture the new values on row updating and do the updates on your own.您不需要在行更新时捕获新值并自行进行更新。

For this you need to set the UpdateCommand为此,您需要设置UpdateCommand

Eg:例如:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:UsersInfoDBConnectionString %>" 
    SelectCommand="SELECT dbo.Divisions.DivisionShortcut, dbo.employee.Username, dbo.employee.Name, dbo.employee.JobTitle, dbo.employee.BadgeNo, dbo.employee.IsActive
        FROM dbo.Divisions INNER JOIN dbo.employee
        ON dbo.Divisions.SapCode = dbo.employee.DivisionCode"
    UpdateCommand="UPDATE Employee SET Name = @Name, JobTitle = @JobTitle, BadgeNo = @BadgeNo
        WHERE Username = @Username">

    <UpdateParameters>
        <asp:Parameter Name="Name" Type="String" />
        <asp:Parameter Name="JobTitle" Type="String" />
        <asp:Parameter Name="BadgeNo" Type="String" />
        <asp:Parameter Name="BadgeNo" Type="String" />
        <asp:Parameter Name="Username" Type="String" />
    </UpdateParameters>               
</asp:SqlDataSource>

Your error really says it all.你的错误真的说明了一切。 Have a look at UpdateCommand . 看看 UpdateCommand

In you UpdateEmployeeInfo function try:在您的UpdateEmployeeInfo函数中尝试:

SqlDataSource1.UpdateCommand =  @"UPDATE Employee SET Name = " + name + ", JobTitle = " + jobTitle + ", BadgeNo = " + badgeNo + " WHERE Username = " + username;
SqlDataSource1.Update();

Note: Not tested注:未测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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