GridView,EDIT,UPDATE

时间:2016-09-14 11:49:07

标签: c# html sql gridview

我用SQL db创建了gridview,我创建了Three Textbox" CountryID"," Name"," CountryNotes",并在网页中添加按钮,当我添加细节时,它将添加到数据库并填充在gridview中。我已完成编辑和更新编码,一切运行完美,但在点击更新按钮细节后更新到网格视图,但文本框不清晰,更新按钮应更改为添加按钮。

我在这里添加 HTMl代码:

<form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="script1" runat="server"></asp:ScriptManager>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <table align="Center" style="width: 50%;">
                        <tr>
                            <td class="auto-style1">
                                <asp:Label ID="Label1" runat="server" Text="CountryID" ForeColor="#CC0000"></asp:Label>
                            </td>
                            <td>
                                <asp:TextBox ID="Text1" runat="server"></asp:TextBox>
                            </td>

                        </tr>
                        <tr>
                            <td class="auto-style1">
                                <asp:Label ID="Label2" runat="server" Text="Name" ForeColor="#CC0000"></asp:Label>
                            </td>
                            <td>
                                <asp:TextBox ID="Text2" runat="server"></asp:TextBox>
                            </td>

                        </tr>
                        <tr>
                            <td class="auto-style1">
                                <asp:Label ID="Label3" runat="server" Text="CountryNotes" ForeColor="#CC0000"></asp:Label>
                            </td>
                            <td>
                                <asp:TextBox ID="Text3" runat="server"></asp:TextBox>
                            </td>
                        </tr>
                        <tr>
                            <td class="auto-style1">
                                <asp:Button ID="Button1" runat="server" Text="Add" BackColor="#CC0000" ForeColor="White" ToolTip="Insert" OnClick="Button1_Click" />
                            </td>
                            <td>
                                <asp:Button ID="Button2" Visible="false" runat="server" BackColor="#CC0000" ForeColor="White" OnClick="Button2_Click" Text="Cancel" />
                            </td>
                        </tr>
                    </table>

                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CountryID" DataSourceID="SqlDataSource1" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowCommand="Row_edit">
                        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                        <Columns>
                            <asp:BoundField DataField="CountryID" HeaderText="CountryID" ReadOnly="True" SortExpression="CountryID" />
                            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                            <asp:BoundField DataField="CountryNotes" HeaderText="CountryNotes" SortExpression="CountryNotes" />
                            <asp:ButtonField ButtonType="Image" ImageUrl="~/Edit.png" CommandName="EditRow" />
                            <asp:ButtonField ButtonType="Image" ImageUrl="~/Delete.png" CommandName="DeleteRow" />
                        </Columns>
                        <EditRowStyle BackColor="#999999" />
                        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#E9E7E2" />
                        <SortedAscendingHeaderStyle BackColor="#506C8C" />
                        <SortedDescendingCellStyle BackColor="#FFFDF8" />
                        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                    </asp:GridView>
                </ContentTemplate>
            </asp:UpdatePanel>






            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues" ConnectionString="<%$ ConnectionStrings:ATSConnectionString %>" DeleteCommand="DELETE FROM [Country1] WHERE [CountryID] = @original_CountryID AND [Name] = @original_Name AND [CountryNotes] = @original_CountryNotes" InsertCommand="INSERT INTO [Country1] ([CountryID], [Name], [CountryNotes]) VALUES (@CountryID, @Name, @CountryNotes)" OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT CountryID, Name, CountryNotes FROM Country1" UpdateCommand="UPDATE [Country1] SET [Name] = @Name, [CountryNotes] = @CountryNotes WHERE [CountryID] = @original_CountryID AND [Name] = @original_Name AND [CountryNotes] = @original_CountryNotes">
                <DeleteParameters>
                    <asp:Parameter Name="original_CountryID" Type="Int32" />
                    <asp:Parameter Name="original_Name" Type="String" />
                    <asp:Parameter Name="original_CountryNotes" Type="String" />
                </DeleteParameters>
                <InsertParameters>
                    <asp:Parameter Name="CountryID" Type="Int32" />
                    <asp:Parameter Name="Name" Type="String" />
                    <asp:Parameter Name="CountryNotes" Type="String" />
                </InsertParameters>
                <UpdateParameters>
                    <asp:Parameter Name="Name" Type="String" />
                    <asp:Parameter Name="CountryNotes" Type="String" />
                    <asp:Parameter Name="original_CountryID" Type="Int32" />
                    <asp:Parameter Name="original_Name" Type="String" />
                    <asp:Parameter Name="original_CountryNotes" Type="String" />
                </UpdateParameters>
            </asp:SqlDataSource>

        </div>
    </form>

我在这里附上 C#代码:

public partial class Country : System.Web.UI.Page
{



    SqlConnection con;
    SqlCommand cmd;
    public void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataBind();
        }

    }





    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Button1.ToolTip == "Insert")
        {
            con = new SqlConnection("Data Source=RYI-SYS-004;Initial Catalog=ATS;Integrated Security=True");
            cmd = new SqlCommand("insert into Country1 (CountryID,Name,CountryNotes) values(@CountryID, @Name, @CountryNotes)", con);

            cmd.Parameters.AddWithValue("@CountryID", Text1.Text);
            cmd.Parameters.AddWithValue("@Name", Text2.Text);
            cmd.Parameters.AddWithValue("@CountryNotes", Text3.Text);
            con.Open();
            cmd.ExecuteNonQuery();

            con.Close();


        }
        else if (Button1.ToolTip == "Update")
        {
            int id = Convert.ToInt32(ViewState["CountryID"]);
            update(id);

        }



    }



    protected void Row_edit(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "EditRow")
        {
            int nRowIndex = Int32.Parse(e.CommandArgument.ToString());
            Int32 nCountryID = Convert.ToInt32(GridView1.DataKeys[nRowIndex].Value);
            GridViewRow row = GridView1.Rows[nRowIndex];
            Text1.Text = row.Cells[0].Text;
            Text2.Text = row.Cells[1].Text;
            Text3.Text = row.Cells[2].Text;
            Button1.ToolTip = "Update";
            Button1.Text = "Update";
            Button2.Visible = true;
            int CountryID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values["CountryID"].ToString());
            ViewState["CountryId"] = CountryID.ToString();

        }

        else if (e.CommandName == "DeleteRow")
        {
            int id = Int32.Parse(e.CommandArgument.ToString());
            GridView1.DeleteRow(id);
        }

    }

    public void update(int id)
    {
        con = new SqlConnection("Data Source=RYI-SYS-004;Initial Catalog=ATS;Integrated Security=True");
        int CountryId = id;
        string str = "update Country1 set Name='" + Text2.Text + "', CountryNotes='" + Text3.Text + "' where CountryID='" + Text1.Text + "'";
        cmd = new SqlCommand(str, con);
        cmd.Parameters.AddWithValue("@Name", Text2.Text);
        cmd.Parameters.AddWithValue("@CountryNotes", Text3.Text);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        GridView1.DataBind();

    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Button1.Text = "Add";
        Button2.Visible = false;
        Text1.Text = "";
        Text2.Text = "";
        Text3.Text = "";
    }

2 个答案:

答案 0 :(得分:1)

您好Dhivyadevi Dhanapal请添加两件事:

  1. 创建清除和更新网格视图的方法。
  2. public void clear()
        {
            Text1.Text = "";
            Text2.Text = "";
            Text3.Text = "";
            GridView1.DataBind();
        }
    

    <强> 2。在添加按钮中调用该方法。

    protected void Button1_Click(object sender, EventArgs e) 
     {
    
     if (Button1.ToolTip == "Insert")
            {
    
              //  con = your Connection String
    
    cmd = new SqlCommand("insert into Country1 (CountryID,Name,CountryNotes) values(@CountryID, @Name, @CountryNotes)", con);
    
                cmd.Parameters.AddWithValue("@CountryID", Text1.Text);
    
                cmd.Parameters.AddWithValue("@Name", Text2.Text);
    
                cmd.Parameters.AddWithValue("@CountryNotes", Text3.Text);
    
                con.Open();
    
                cmd.ExecuteNonQuery();
    
                con.Close();
    
            }
    
            else if (Button1.ToolTip == "Update")
    
            {
    
                int id = Convert.ToInt32(ViewState["CountryID"]);
    
                update(id);
    
    
    
            }
    
    
            clear();
    
        }
    

答案 1 :(得分:0)

我首先要说的是,我认为你是一名新程序员。我给你的第一个建议是你不应该只调用文本框和按钮textbox1 textbox2和Button1和Button2。这是新手的工作。在前端的TextBox ID区域中将它们称为有意义的名称,例如txtCountryID和txtCountryName。同样,Button1应该被称为btnAdd,Button2应该被称为btnCancel,然后你应该分别为它们创建后端函数。当您从一开始就正确地开始设计软件时,您可以在以后节省您的困惑和错误。即使它像调用按钮和文本框有意义的名称一样简单。这一切都是为了清楚地思考,这是它将帮助你做的事情。

即使你的问题还不清楚,但是当你明确地在Button2_Click中清除代码时,你问为什么你的文本框没有被清除。简单的答案是你可能没有按下Button2,它应该是取消按钮,但你只是叫做Button2,这是不可接受的编码练习。同时更改按钮名称是一种非常简单的做法。不要更改按钮名称,而是保持按钮名称相同,并为不同的操作添加更多按钮。