vb.net DataGridView 验证:如何确保行的每个单元格都包含一个值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13215431/
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 11:00:45  来源:igfitidea点击:

DataGridView validation: How do I ensure that each cell of a row contains a value?

vb.netvalidationdatagridview

提问by ???ěxě?

I have a DataGridViewcontrol on my form. It has 6 columns and 6 rows (which will never change). When a user enters data in a cell under any column, I want to make sure they fill in the rest of the cells for that row. So basically if they put data in row 0 – column 0, I want to ensure that row 0 – column 1, row 0 – column 2 and so on... have data in them. I need this for validation reasons before this will be committed to the database. If the fields are not all filled in for that row, I want to display a message containing the rows that need to be fixed.

DataGridView对我的表单有一个控制。它有 6 列和 6 行(永远不会改变)。当用户在任何列下的单元格中输入数据时,我想确保他们填写该行的其余单元格。所以基本上,如果他们把数据放在第 0 行 – 第 0 列,我想确保第 0 行 – 第 1 列、第 0 行 – 第 2 列等等......其中有数据。在将其提交给数据库之前,出于验证原因,我需要它。如果该行的字段未全部填写,我想显示一条消息,其中包含需要修复的行。

Any help is greatly appreciated!

任何帮助是极大的赞赏!

Here's an update, I have figured out what needed to be done.

这是更新,我已经弄清楚需要做什么。

Private Sub ValidateYear()

    Dim oInvYear As New Collection
    Dim oErrorMsg As New System.Text.StringBuilder
    Dim blnErrFound As Boolean = False

    'Loop through year column and check for number, if blank skip'
    For i As Integer = 0 To dgvIntervals.Rows.Count - 1
        If Not String.IsNullOrEmpty(dgvIntervals.Rows(i).Cells(4).Value) Then
            If Not IsNumeric(dgvIntervals.Rows(i).Cells(4).Value) Then
                oInvYear.Add(i + 1)
                blnErrFound = True
            End If
        End If
    Next

    'If errors found, lets append them to our message'
    If blnErrFound Then
        oErrorMsg.Append("PLEASE FIX ERRORS BELOW BEFORE PROCEEDING")
        oErrorMsg.AppendLine("")
        oErrorMsg.Append(vbCrLf)

    'Get our year count errors'
    If oInvYear.Count > 0 Then
        oErrorMsg.Append("* Year must be a number- ")
        oErrorMsg.Append("Line(s): ")
        For i As Integer = 1 To oInvYear.Count
            If i >= 2 Then
                oErrorMsg.Append(", ")
            End If
            oErrorMsg.Append(oInvYear.Item(i).ToString)
        Next
        oErrorMsg.Append(vbCrLf)
    End If

    'Show them to our user'
    MsgBox(oErrorMsg.ToString)

End Sub 

采纳答案by Hamish Smith

Use the CellValidating or RowValidating events of the DataGridView control to validate the data that has been entered by the user.

使用 DataGridView 控件的 CellValidating 或 RowValidating 事件来验证用户输入的数据。

Private Sub OnRowValidating(ByVal sender As Object, ByVal args As DataGridViewCellCancelEventArgs) Handles DataGridView1.RowValidating
  Dim row As DataGridViewRow = DataGridView1.Rows(args.RowIndex)
  For Each cell As DataGridViewCell In row.Cells
     If String.IsNullOrEmpty(cell.Value.ToString()) Then
        'show a message box or whatever...
     End If
  Next
End Sub

回答by luis_laurent

Well in this scenario I recommend you to read every cell from every row that you have, and when you find a value in any cell you need to make sure that there are values for the other cells.

那么在这种情况下,我建议您从您拥有的每一行中读取每个单元格,并且当您在任何单元格中找到一个值时,您需要确保其他单元格也有值。

I did a little sample for you, I hope this help you with your problem.

我为你做了一个小样本,我希望这能帮助你解决你的问题。

At first I created this entity to fill my gridview:

起初我创建了这个实体来填充我的 gridview:

  public class MyEntity
    {
        public string ID { get; set; }

        public string Name { get; set; }

        public string LastName { get; set; }
    }

This is the code on my aspx page

这是我的 aspx 页面上的代码

<form id="form1" runat="server">
    <div>
        <asp:GridView ID="grvData" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField HeaderText="ID" >
                    <ItemTemplate >
                        <asp:Label ID="lblID" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField  HeaderText="Name">
                    <ItemTemplate>
                        <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField  HeaderText="Last Name">
                    <ItemTemplate>
                        <asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName") %>'></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <br />
        <asp:Button ID="btnValidate" runat="server" Text="Validate" OnClick="btnValidate_Click" />
        <br />
        <asp:Label ID="lblMessage" runat="server" ForeColor="Red" Text="">

        </asp:Label>
    </div>
    </form>

Then on my code behind

然后在我后面的代码上

public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                List<MyEntity> data = GenerateData();
                this.grvData.DataSource = data;
                this.grvData.DataBind();
            }
        }

        protected void btnValidate_Click(object sender, EventArgs e)
        {
            int columns = this.grvData.Columns.Count - 1;
            foreach (GridViewRow row in this.grvData.Rows)
            {
                int count = columns;
                TextBox tbName = row.Cells[1].FindControl("txtName") as TextBox;
                TextBox tbLastName = row.Cells[2].FindControl("txtLastName") as TextBox;
                if (!string.IsNullOrWhiteSpace(tbName.Text))
                {
                    count--;
                }
                if (!string.IsNullOrWhiteSpace(tbLastName.Text))
                {
                    count--;
                }
                if (count != columns && count != 0)
                {
                    this.lblMessage.Text = "Invalid input, you need to supply data for every field.";
                    break;
                }
            }
        }

        private List<MyEntity> GenerateData()
        {
            List<MyEntity> list = new List<MyEntity>();
            for (int i = 0; i < 5; i++)
            {
                MyEntity entity = new MyEntity() { ID = Guid.NewGuid().ToString() };
                list.Add(entity);
            }
            return list;
        }
    }

As you can see is pretty simple, I would not recommend you to use this approach if you are loading too many records with many columns, because that could affect performance, but in your case I think this should works.

正如您所看到的,这非常简单,如果您加载了太多列的记录,我不建议您使用这种方法,因为这可能会影响性能,但在您的情况下,我认为这应该有效。

PS. My answer is with visual C#, because when I read it you did not mention the language, and now you just changed it.

附注。我的答案是visual C#,因为我读的时候你没有提到语言,现在你只是改变了它。