使用验证和文本框编辑,删除和更新gridview

时间:2013-03-05 08:03:15

标签: asp.net c#-4.0 gridview

我有四个文本框,两个按钮,一个网格视图和一个复选框,我在每个文本框上放置需要字段验证我有一个数据库,这样当我在文本框中输入值并按提交按钮数据存储在数据库中,并在我使用数据表时显示在网格中。我现在在网格视图中编辑,删除和更新链接,当我点击编辑或删除显示的链接验证错误消息时,我不会在我的网格中进行更改。谁可以帮我这个事。

提前致谢

我的aspx代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>

</head>
<body style="height: 191px">
<form id="form1" runat="server">
<div>
    <table class="style1">
        <tr>
            <td class="style3">
                FirstName</td>
            <td>
    <asp:TextBox ID="tFirstName" runat="server"></asp:TextBox>
    &nbsp;&nbsp;&nbsp;&nbsp;
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                    ControlToValidate="tFirstName" ErrorMessage="Enter First Name">*</asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td class="style3">
                Last name</td>
            <td>
    <asp:TextBox ID="tLastName" runat="server"></asp:TextBox>
    &nbsp;&nbsp;&nbsp;&nbsp;
                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
                    ControlToValidate="tLastName" ErrorMessage="Enter Last Name">*</asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td class="style3">
                Age</td>
            <td>
    <asp:TextBox ID="tAge" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" 
                    ControlToValidate="tAge" ErrorMessage="" dalega">*</asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td class="style7">
                Is Active</td>
            <td class="style8">
                <asp:CheckBox ID="dropActive" runat="server" />
            </td>
        </tr>
        <tr>
            <td class="style3">
                Auto ID</td>
            <td>
                <asp:TextBox ID="autoID" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" 
                ControlToValidate="autoID" ErrorMessage="Marzi hai teri">*</asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td class="style6">
                </td>
            <td class="style5">
       <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Sumit" ValidationGroup="abc"/>
    <input type="reset" />
                <br />   
                <asp:ValidationSummary ID="ValidationSummary1" runat="server" Height="72px" />
            </td>
        </tr>
        <tr>
            <td class="style4" colspan="2">
                 <asp:Label ID="lblMessage" runat="server" ForeColor="Green" EnableViewState="false" />
  <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="false" Width="36%" OnRowEditing="EditRow" OnRowCancelingEdit="CancelEditRow" OnRowUpdating="UpdateRow" DataKeyNames="AutoId" OnRowDeleting="DeleteRow" AllowPaging="true" OnPageIndexChanging="ChangePage" AllowSorting="True">
<Columns>
    <asp:TemplateField HeaderText="Edit">
        <ItemTemplate>
            <asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit" />
        </ItemTemplate>
        <EditItemTemplate>
            <asp:LinkButton ID="lnkUpdate" runat="server" Text="Update" CommandName="Update" />
            <asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel" CommandName="Cancel" />
        </EditItemTemplate>
    </asp:TemplateField>
    <asp:BoundField HeaderText="AutoId" DataField="AutoId" ReadOnly="true" />
    <asp:TemplateField HeaderText="First Name">
        <ItemTemplate>
            <%# Eval("FirstNAme") %></ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName") %>'/>
        </EditItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Last Name">
        <ItemTemplate>
            <%# Eval("LastName") %></ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName") %>'/>
        </EditItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Age">
        <ItemTemplate>
            <%# Eval("Age") %></ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age") %>' Columns="3" />
           <asp:RequiredFieldValidator ID="REw" runat="server" ControlToValidate="txtAge" Text="*" /> 
        </EditItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Is Active?">
        <ItemTemplate>
            <%# Eval("Active").ToString().Equals("True") ? "Yes" : "No" %>
        </ItemTemplate>
        <HeaderStyle HorizontalAlign="Left" />
        <EditItemTemplate>
            <asp:DropDownList ID="dropActive" runat="server" SelectedValue='<%# Eval("Active") %>'>
            <asp:ListItem Text="Yes" Value="True" />
            <asp:ListItem Text="No" Value="False" />
            </asp:DropDownList>
        </EditItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Delete?">
        <ItemTemplate>
            <span onclick="return confirm('Are you sure to delete?')">
            <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" ForeColor="Red" CommandName="Delete" />
            </span>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#efefef" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
 </asp:GridView>
                    </table>
                    </div>
                    </form>
                   </body>
                   </html>

aspx.cs的代码:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        PopulateData();
    }
}
protected void EditRow(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    this.PopulateData();
}
protected void CancelEditRow(object sender, GridViewCancelEditEventArgs e)
{
    GridView1.EditIndex = -1;
    this.PopulateData();
}
protected void DeleteRow(object sender, GridViewDeleteEventArgs e)
{
    var autoID = GridView1.DataKeys[e.RowIndex].Value;
    using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=EMS;Integrated Security=True"))
    {
        string sql = "Delete from PersonalDetail" +" where AutoId = @AutoId";
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            cmd.Parameters.AddWithValue("@AutoId", autoID);
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
    }
    lblMessage.Text ="Record has been deleted successfully !";
    lblMessage.ForeColor = System.Drawing.
    Color.Red;
    this.PopulateData();
}
protected void ChangePage(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    this.PopulateData();
}
protected void UpdateRow(object sendedr, GridViewUpdateEventArgs e)
{
    var autoID = GridView1.DataKeys[e.RowIndex].Value;
    GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
    TextBox tFirstName = row.FindControl("txtFirstName") as TextBox;
    TextBox tLastName = row.FindControl("txtLastName") as TextBox;
    TextBox tAge = row.FindControl("txtAge") as TextBox;
    DropDownList dropActive = row.FindControl("dropActive") as DropDownList;
    using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=EMS;Integrated Security=True"))
    {
        string sql = "Update PersonalDetail set FirstName = @FirstName,LastName=@LastName, Age= @Age, Active = @Active" + " where AutoId = @AutoId";
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            cmd.Parameters.AddWithValue("@FirstName", tFirstName.Text.Trim());
            cmd.Parameters.AddWithValue("@LastName", tLastName.Text.Trim());
            cmd.Parameters.AddWithValue("@Age", tAge.Text.Trim());
            cmd.Parameters.AddWithValue("@Active", dropActive.SelectedValue);
            cmd.Parameters.AddWithValue("@AutoId", autoID);
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
    }
    lblMessage.Text ="Record updated successfully !";
    GridView1.EditIndex = -1;
    this.PopulateData();
}
private void PopulateData()
{
    DataTable table = new DataTable();
    using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=EMS;Integrated Security=True"))
    {
        string sql = "Select * from PersonalDetail";
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
            {
                ad.Fill(table);
            }
        }
    }
    GridView1.DataSource = table;
    GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=EMS;Integrated Security=True");
    con.Open();

    string FirstName = tFirstName.Text;
    string LastName = tLastName.Text;
    string Age = tAge.Text;
    string Active = dropActive.Text;
    string AutoId = autoID.Text;

    using (SqlCommand cmd = con.CreateCommand())
    {
        cmd.CommandText = "insert into PersonalDetail(FirstName,LastName,Age,Active,AutoId) values('" + FirstName + "','" + LastName + "','" + Age + "','" + Active + "','" + AutoId + "')";
        cmd.Parameters.AddWithValue("@FirstName", tFirstName.Text.Trim());
        cmd.Parameters.AddWithValue("@LastName", tLastName.Text.Trim());
        cmd.Parameters.AddWithValue("@Age", tAge.Text.Trim());
        cmd.Parameters.AddWithValue("@Active", dropActive.Text.Trim());

        cmd.Parameters.AddWithValue("@AutoId", autoID.Text.Trim());
        cmd.ExecuteNonQuery();
    }
    con.Close();
    tFirstName.Text = string.Empty;
    tLastName.Text = string.Empty;
    tAge.Text = string.Empty;
    dropActive.Text = string.Empty;
    tFirstName.Focus();
}

3 个答案:

答案 0 :(得分:3)

  

您的Validation控件都没有Validation Group   将其添加到您的所有RequiredFieldValidator

ValidationGroup="SomeName"
  

确保所有RequiredFieldValidator具有相同的ValidationGroup
  现在最后将ValidationGroup="SomeName"添加到Button控件中,单击该控件时会引发验证控件。

答案 1 :(得分:1)

我只是使用this.populate();在按钮1上显示网格视图后,在文本框中输入详细信息,感谢您的回复人员。

答案 2 :(得分:0)

尝试从链接CauseValidation="false"

中删除验证检查
<ItemTemplate>
    <asp:LinkButton CauseValidation="false" ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>