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

时间:2012-11-04 02:15:37

标签: vb.net validation datagridview

我的表单上有DataGridView控件。它有6列6行(永远不会改变)。当用户在任何列下的单元格中输入数据时,我想确保它们填充该行的其余单元格。所以基本上如果他们把数据放在第0行 - 第0列,我想确保第0行 - 第1列,第0行 - 第2列......依此类推......在将此提交到数据库之前,我需要此验证原因。如果没有为该行填写所有字段,我想显示一条消息,其中包含需要修复的行。

非常感谢任何帮助!

这是一个更新,我已经找到了需要做的事情。

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 

2 个答案:

答案 0 :(得分:0)

在这种情况下,我建议您阅读每行中的每个单元格,当您在任何单元格中找到值时,您需要确保其他单元格的值。

我为你做了一些示例,希望这可以帮助你解决问题。

首先我创建了这个实体来填充我的gridview:

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

        public string Name { get; set; }

        public string LastName { get; set; }
    }

这是我的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>

然后在我的代码背后

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;
        }
    }

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

PS。我的答案是视觉C#,因为当我读到它时你没有提到语言,现在你只是改了它。

答案 1 :(得分:0)

使用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
相关问题