使用Gridview中的文本框将数据更新到SQL Server

时间:2015-02-12 17:26:18

标签: asp.net gridview

至少可以说,我无法计算如何在文本框中键入信息,以便在Notes列下使用更新按钮发布到SQL数据库。每次编辑文本框中的信息时,新信息都应该发布到SQL数据库,但我不知道如何开始。任何帮助表示赞赏。

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" 
        AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE" 
        BorderStyle="None" BorderWidth="1px" CellPadding="4" 
        DataSourceID="SqlDataSource3" ForeColor="Black" GridLines="Vertical">
        <AlternatingRowStyle BackColor="White" />
        <Columns>
            <asp:BoundField DataField="LastName" HeaderText="Last Name" 
                SortExpression="LastName" />
            <asp:BoundField DataField="FirstName" HeaderText="First Name" 
                SortExpression="FirstName" />
            <asp:BoundField DataField="CompanyName" HeaderText="Company" 
                SortExpression="CompanyName" />
            <asp:TemplateField HeaderText="Conf Fee" SortExpression="ConferenceFee">
            <ItemTemplate>
            <%# Convert.ToDecimal(Eval("ConferenceFee")).ToString("#,##0.00") %>
            </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Total Cost" SortExpression="TotalCost">
            <ItemTemplate>
            <%# Convert.ToDecimal(Eval("TotalCost")).ToString("#,##0.00") %>
            </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="PaymentInfoID" HeaderText="Invoice" 
                SortExpression="PaymentInfoID" />
            <asp:TemplateField HeaderText="Notes" SortExpression="Notes">
            <ItemTemplate>
                <asp:TextBox ID="notesTXTBOX" runat="server"></asp:TextBox>
            </ItemTemplate>
            </asp:TemplateField>
            <asp:ButtonField ButtonType="Button" CommandName="Update" Text="Update" />
        </Columns>
        <FooterStyle BackColor="#CCCC99" />
        <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
        <RowStyle BackColor="#F7F7DE" />
        <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
        <SortedAscendingCellStyle BackColor="#FBFBF2" />
        <SortedAscendingHeaderStyle BackColor="#848384" />
        <SortedDescendingCellStyle BackColor="#EAEAD3" />
        <SortedDescendingHeaderStyle BackColor="#575357" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConfOnline %>" 
        SelectCommand="SELECT cr.ConferenceID, p.LastName, p.FirstName, c.CompanyName, pay.ConferenceFee, pay.PaymentInfoID, pay.Notes, pay.TotalCost FROM Conference cr, People p, Company c, PaymentInfo pay WHERE cr.UsersIDNum=p.UsersIDNum AND c.CompanyID=p.CompanyIDNum AND pay.PaymentInfoID=cr.PaymentInfoIDNum AND cr.ConferenceIDNum=@confID AND cr.Deleted='N' AND pay.Deleted='N' ORDER BY c.CompanyName">
        <SelectParameters>
            <asp:ControlParameter ControlID="conferenceDDL" Name="confID" 
                PropertyName="SelectedValue" />
        </SelectParameters>
    </asp:SqlDataSource>

1 个答案:

答案 0 :(得分:0)

以下是具有GridView控件的Label的标记,该控件将是SerialNo,3 TextBox控件用于插入文本,而dropdown list用于选择一些默认值。

        <asp:GridView ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="false"
        OnRowDeleting="GridView1_RowDeleting">
        <Columns>
            <asp:TemplateField HeaderText="Serial No">
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Container.DataItemIndex + 1 %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Col1">
                <ItemTemplate>
                    <asp:TextBox runat="server" ID="txt1" Text='<%# Eval("Column1") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Col2">
                <ItemTemplate>
                    <asp:TextBox ID="txt2" runat="server" Text='<%# Eval("Column2") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Col3">
                <ItemTemplate>
                    <asp:TextBox ID="txt3" runat="server" Text='<%# Eval("Column3") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="DropDown">
                <ItemTemplate>
                    <asp:DropDownList ID="DropDownList1" runat="server">
                        <asp:ListItem>London</asp:ListItem>
                        <asp:ListItem>Paris</asp:ListItem>
                        <asp:ListItem>New Delhi</asp:ListItem>
                        <asp:ListItem>New York</asp:ListItem>
                    </asp:DropDownList>
                </ItemTemplate>
                <FooterStyle HorizontalAlign="Right" />
                <FooterTemplate>
                    <asp:Button ID="btnAddNewRow" runat="server" Text="AddRow" OnClick="Add" />
                </FooterTemplate>
            </asp:TemplateField>
            <asp:CommandField ButtonType="Button" ShowDeleteButton="true" />
        </Columns>
    </asp:GridView>

现在背后的代码:

List<string> newlist = new List<string>();
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //SetInitialRow();
                var table = CreateDataTable();
                table.Rows.Add("", "", "");
                BindGridView(table);
            }
        //Sets the first empty row to the grid view
        private DataTable CreateDataTable()
        {
            var dt = new DataTable
            {
                Columns = { "Column1", "Column2", "Column3","Column4" }
            };
            return dt;
        }

        private void BindGridView(DataTable table)
        {
            GridView1.DataSource = table;
            GridView1.DataBind();
            for(int i=0;i<GridView1.Rows.Count-1;i++)
            {
                DropDownList ddl2 = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
                ddl2.ClearSelection();
                ddl2.Items.FindByText(newlist[i]).Selected = true;
            }
        }
protected void Add(object sender, EventArgs e)
        {
            var newTable = PopulateTableFromGridView();
            newTable.Rows.Add("", "", "");
            BindGridView(newTable);
}
private DataTable PopulateTableFromGridView()
        {
            var table = CreateDataTable();
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                //extract the TextBox values
                TextBox box1 = (TextBox)GridView1.Rows[i].FindControl("txt1");
                TextBox box2 = (TextBox)GridView1.Rows[i].FindControl("txt2");
                TextBox box3 = (TextBox)GridView1.Rows[i].FindControl("txt3");
                DropDownList ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
                table.Rows.Add(box1.Text, box2.Text, box3.Text,ddl.SelectedItem.Text);
                newlist.Add(ddl.SelectedItem.Text);
            }
            return table;
        }
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var dt = PopulateTableFromGridView();

            if (dt.Rows.Count > 1)
            {
                dt.Rows[e.RowIndex].Delete();
            }
            BindGridView(dt);
}
protected void btnSavetoDB_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Serial No",typeof(string)),
                        new DataColumn("Column1", typeof(string)),
                        new DataColumn("Column2", typeof(string)),
                        new DataColumn("Column3",typeof(string)),
                        new DataColumn("Column4", typeof(string)) });
            foreach (GridViewRow row in GridView1.Rows)
            {
                Label serNo = row.FindControl("Label1") as Label;
                TextBox txt1 = row.FindControl("txt1") as TextBox;
                TextBox txt2 = row.FindControl("txt2") as TextBox;
                TextBox txt3 = row.FindControl("txt3") as TextBox;
                DropDownList ddl=row.FindControl("DropDownList1") as DropDownList;
                    dt.Rows.Add(serNo.Text,txt1.Text, txt2.Text, txt3.Text, ddl.SelectedItem.Text);    
            }

            if (dt.Rows.Count > 0)
            {
                string consString = ConfigurationManager.ConnectionStrings["DBConnect"].ConnectionString;
                using (SqlConnection con = new SqlConnection(consString))
                {
                    using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                    {
                        //Set the database table name
                        sqlBulkCopy.DestinationTableName = "dbo.GridTable";

                        //[OPTIONAL]: Map the DataTable columns with that of the database table
                        sqlBulkCopy.ColumnMappings.Add("Serial No", "Serial No.");
                        sqlBulkCopy.ColumnMappings.Add("Column1", "Column1");
                        sqlBulkCopy.ColumnMappings.Add("Column2", "Column2");
                        sqlBulkCopy.ColumnMappings.Add("Column3", "Column3");
                        sqlBulkCopy.ColumnMappings.Add("Column4", "Column4");
                            con.Open();
                            sqlBulkCopy.WriteToServer(dt);
                            con.Close();
                    }
                }
            }
        }

基本上上面的代码片段会帮助你这样: 在PageLoad上,网格将有一个空行,您可以在其中编写自己的值。有一个AddRow按钮可以帮助你添加一行,还有删除按钮来删除一个特定的行。

快照: enter image description here