vb.net 如何在 Gridview 中编辑数据表行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18455407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:48:06  来源:igfitidea点击:

How to edit datatable rows in Gridview

vb.netgridviewdatatableviewstate

提问by Josh_with_questions

and thanks for viewing my post. I currently have a gridview populated by a datatable in viewstate. My touble is I am unable to edit the rows. I will show you the code below, but what happens when I click edit is the textbox in cell 2 becomes empty, but the text in cell 1 doesn't. Here is code I have so far starting with creating the data table:

并感谢您查看我的帖子。我目前有一个由 viewstate 中的数据表填充的 gridview。我的问题是我无法编辑行。我将向您展示下面的代码,但是当我单击编辑时会发生什么情况是单元格 2 中的文本框变为空,但单元格 1 中的文本没有。这是我迄今为止从创建数据表开始的代码:

GridView markup:

GridView 标记:

<asp:GridView ID="GridView2" runat="server" Visible="False" 
                    AutoGenerateColumns="false" ShowFooter="True" 
                    AutoGenerateDeleteButton="True" AutoGenerateEditButton="True">
                <Columns>

    <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
    <asp:TemplateField HeaderText="Action Item">
        <ItemTemplate>
            <asp:TextBox ID="TextBox1" Width="500px" TextMode="MultiLine" runat="server"></asp:TextBox>

        </ItemTemplate>

        <FooterTemplate>
         <asp:Button ID="ButtonAdd" OnClick="ButtonAdd_Click" runat="server" Text="Add New Row" />
        </FooterTemplate>
        </asp:TemplateField>

    </Columns>
                </asp:GridView>

'set initial dt :
Private Sub SetInitialRow()
        Dim dt As New DataTable()
        Dim dr As DataRow = Nothing
        dt.Columns.Add(New DataColumn("RowNumber", GetType(String)))
        dt.Columns.Add(New DataColumn("Action Item", GetType(String)))
        dr = dt.NewRow()
        dr("RowNumber") = 1
        dr("Action Item") = String.Empty
        dt.Rows.Add(dr)
        'dr = dt.NewRow();

        'Store the DataTable in ViewState
        ViewState("CurrentTable") = dt

        GridView2.DataSource = dt
        GridView2.DataBind()

'Then I add a row with a button click in gridview footer:

'然后我在 gridview 页脚中添加一行并单击按钮:

Private Sub AddNewRowToGrid()
        Dim rowIndex As Integer = 0

        If ViewState("CurrentTable") IsNot Nothing Then
            Dim dtCurrentTable As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
            Dim drCurrentRow As DataRow = Nothing
            If dtCurrentTable.Rows.Count > 0 Then
                For i As Integer = 1 To dtCurrentTable.Rows.Count
                    'extract the TextBox values
                    Dim box1 As TextBox = DirectCast(GridView2.Rows(rowIndex).Cells(1).FindControl("TextBox1"), TextBox)

                    drCurrentRow = dtCurrentTable.NewRow()
                    drCurrentRow("RowNumber") = i + 1
                    drCurrentRow("Action Item") = box1.Text

                    rowIndex += 1
                Next
                'add new row to DataTable
                dtCurrentTable.Rows.Add(drCurrentRow)
                'Store the current data to ViewState
                ViewState("CurrentTable") = dtCurrentTable

                'Rebind the Grid with the current data
                GridView2.DataSource = dtCurrentTable
                GridView2.DataBind()
            End If
        Else
            Response.Write("ViewState is null")
        End If

        'Set Previous Data on Postbacks
        SetPreviousData()
    End Sub

Now here is where I have trouble. This code updates the row number (first column), but does nothing to the second column. It actually deletes the content.

现在这是我遇到麻烦的地方。此代码更新行号(第一列),但对第二列不执行任何操作。它实际上删除了内容。

Protected Sub GridView2_RowEditing(sender As Object, e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView2.RowEditing
        'Set the edit index.
        Dim dt As DataTable = CType(ViewState("CurrentTable"), DataTable)
        GridView2.EditIndex = e.NewEditIndex
        GridView2.DataSource = ViewState("CurrentTable")
        GridView2.DataBind()
    End Sub

Protected Sub GridView2_RowUpdating(sender As Object, e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView2.RowUpdating

'Retrieve the table from the session object.
Dim dt As DataTable = CType(ViewState("CurrentTable"), DataTable)

'Update the values.
Dim row = GridView2.Rows(e.RowIndex)
dt.Rows(row.DataItemIndex)("RowNumber") = (CType((row.Cells(1).Controls(0)), TextBox)).Text
 dt.Rows(row.DataItemIndex)("Action Item") = (CType((row.Cells(2).FindControl("TextBox1")), TextBox).Text)

'Reset the edit index.
GridView2.EditIndex = -1

'Bind data to the GridView control.
GridView2.DataSource = ViewState("CurrentTable")
GridView2.DataBind()
End Sub

Could you please help me figure out where I'm going wrong? Thank you!

你能帮我弄清楚我哪里出错了吗?谢谢!

Josh

乔希

回答by Karl Anderson

Here is the markup you need to create an EditItemTemplatewithin your TemplateField:

这里是你的标记需要创建一个EditItemTemplate你中TemplateField

<asp:GridView ID="GridView2" runat="server" Visible="False" AutoGenerateColumns="false"
              ShowFooter="True" 
              AutoGenerateDeleteButton="True" AutoGenerateEditButton="True">
    <Columns>
        <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
        <asp:TemplateField HeaderText="Action Item">
            <ItemTemplate>
                <asp:TextBox ID="TextBox1" Width="500px" TextMode="MultiLine" runat="server"></asp:TextBox>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox id="EditActionItemTextBox" runat="server" Width="500px" TextMode="MultiLine"></asp:TextBox>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:Button ID="ButtonAdd" OnClick="ButtonAdd_Click" runat="server" Text="Add New Row" />
            </FooterTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Now in your code-behind where you are updating your data table, do this:

现在在您更新数据表的代码隐藏中,执行以下操作:

'Update the values.
Dim row = GridView2.Rows(e.RowIndex)
dt.Rows(row.DataItemIndex)("RowNumber") = (CType((row.Cells(1).Controls(0)), TextBox)).Text
dt.Rows(row.DataItemIndex)("Action Item") = (CType((row.FindControl("EditActionItemTextBox")), TextBox).Text)

Note: In your <ItemTemplate>you may want to consider making the control read-only so that your users know they cannot change the value, usually when a user sees a text box they think they can edit the content, but it completely makes sense to have an editable text box in edit mode of your grid view. To change the the <ItemTemplate>text box to read-only, just add ReadOnly="True", like this:

注意:在您<ItemTemplate>可能需要考虑将控件设为只读,以便您的用户知道他们无法更改该值,通常当用户看到一个文本框时,他们认为他们可以编辑内容,但拥有一个完全有意义的网格视图编辑模式下的可编辑文本框。要将<ItemTemplate>文本框更改为只读,只需添加ReadOnly="True",如下所示:

<ItemTemplate>
    <asp:TextBox ID="TextBox1" Width="500px" TextMode="MultiLine" 
                 runat="server" ReadOnly="True"></asp:TextBox>
</ItemTemplate>

Depending upon the browser, the control will have a slight gray tinge to it. The user will be able to click on the text, but will not be able to change the text.

根据浏览器的不同,控件将带有轻微的灰色调。用户将能够单击文本,但不能更改文本。