簡體   English   中英

使用 asp.net 和 C# 將數據插入 gridview

[英]Inserting data into gridview using asp.net and C#

我最近參與了一個小型項目,並嘗試在其中使用帶有 SQL 的 asp.net。 我面臨的問題是插入功能不起作用,盡管編輯和刪除在同一頁面上工作得很好。 這是 home2.aspx 文件

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home2.aspx.cs" Inherits="DBPROJECT.Home2"  %>

<!DOCTYPE html>

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

  </head>
  <body style="background-image:url(img1.jpg)"  >
  <form id="form2" runat="server">
  <asp:GridView ID="ab" runat="server" Font-Names="Arial"
HorizontalAlign="Center" BackColor="White" BorderColor="#CC9966"   
BorderStyle="None" BorderWidth="1px" 
     CellPadding="4" AutoGenerateColumns="False" 
OnRowEditing="ab_RowEditing" OnRowCancelingEdit="ab_RowCancelingEdit" 
OnRowDeleting="ab_RowDeleting" OnRowUpdating="ab_RowUpdating" 
EnableViewState="False" ><AlternatingRowStyle HorizontalAlign="Center" />
 <Columns>
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
<asp:TemplateField HeaderText="Registration Number" HeaderStyle-
HorizontalAlign="Left">
<EditItemTemplate>
<asp:Label ID="aa" runat="server" Text='<%# Bind("reg_no") %>'></asp:Label>
</EditItemTemplate>

<ItemTemplate>
<asp:Label ID="lblItemNo" runat="server" Text='<%# Bind("reg_no") %>'>
</asp:Label>
</ItemTemplate>

</asp:TemplateField>
<asp:TemplateField HeaderText="Name Of NGO" HeaderStyle-
HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="bb" runat="server" Text='<%# Bind("nname") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblItemName" runat="server" Text='<%# Bind("nname") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="cc"  runat="server" Text='<%# Bind("address") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblTotalUnits" runat="server" Text='<%# Bind("address") %>'>
</asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="OwnerID" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:Label ID="dd" runat="server" Text='<%# Bind("owner_id") %>'>
</asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblItemNoo" runat="server" Text='<%# Bind("owner_id") %>'>
</asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>

</asp:TemplateField>
</Columns>
<EditRowStyle HorizontalAlign="Center" VerticalAlign="Middle" />
      <EmptyDataRowStyle HorizontalAlign="Center" /> 
      <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
      <HeaderStyle Font-Bold="True" BackColor="#990000" ForeColor="#FFFFCC" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<RowStyle HorizontalAlign="Center" BackColor="White" ForeColor="#330099" />
      <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
</asp:GridView>
<br />
<asp:Label runat="server" text="Enter the registration number" Font-Bold="True" ForeColor="White" BackColor="Black"></asp:Label>
    <asp:TextBox runat="server" ID="A1" ></asp:TextBox>
<br />
<br />
<asp:Label runat="server" text="Enter the name of NGO   " Font-Bold="True" 
        ForeColor="White" BackColor="Black"></asp:Label>
<asp:TextBox runat="server" ID="A2" ></asp:TextBox>
<br />
<br />
<asp:Label runat="server"  text="Enter the address   " Font-Bold="True" 
 ForeColor="White" BackColor="Black"></asp:Label>
<asp:TextBox runat="server" ID="A3" ></asp:TextBox>
<br />
<br />
<asp:Label runat="server"  text="Enter the owner's ID    " Font-Bold="True" 
        ForeColor="White" BackColor="Black"></asp:Label>
<asp:TextBox runat="server" ID="A4" ></asp:TextBox>
<br />
<br />
<div>
<asp:Button runat="server" Text="Insert" ID="Button1"OnClick="Button1_Click"
            BackColor="White" Font-Bold="True" Font-Size="Large" ForeColor="Maroon"/>
</div>
</form>
</body>
</html>

這是 aspx.cs 文件

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using DBPROJECT.DAL;

namespace DBPROJECT
{
    public partial class Home2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
    {
        LoadGrid();
    }

    public void LoadGrid()
    {
        myDAL objMyDal = new myDAL();
        ab.DataSource = objMyDal.SelectItem(); 
         ab.DataBind();

    }
    protected void ab_RowEditing(object sender, GridViewEditEventArgs e)
    {
        ab.EditIndex = e.NewEditIndex;
        LoadGrid();

    }

    protected void ab_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = (GridViewRow)ab.Rows[e.RowIndex];
        Label a1 = (Label)ab.Rows[e.RowIndex].FindControl("aa");
        TextBox a2 = (TextBox)ab.Rows[e.RowIndex].FindControl("bb");
        TextBox a3 = (TextBox)ab.Rows[e.RowIndex].FindControl("cc");
        Label a4 = (Label)ab.Rows[e.RowIndex].FindControl("dd");


        int reg_no = Convert.ToInt32(a1.Text.ToString());
        string nname = a2.Text.ToString();
        string address = a3.Text.ToString();
        int owner1 = Convert.ToInt32(a4.Text.ToString());

        myDAL objMyDal = new myDAL();
        objMyDal.UpdateItem(reg_no, nname, address);
         //   ======================================================
            ab.EditIndex = -1;
            LoadGrid();
    }

    protected void ab_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        myDAL objMyDal = new myDAL();
        GridViewRow row = ab.Rows[e.RowIndex];
        Label itemLabel = (Label)row.FindControl("lblItemNo");
        int ItemID = Convert.ToInt32(itemLabel.Text.ToString());
        int result = objMyDal.DeleteItem(ItemID);
        if (result == -1)
        {
            ab.DataSource = objMyDal.SelectItem();
            ab.DataBind();
        }
        else
        {
            string message = "No row deleted";
            ClientScript.RegisterOnSubmitStatement(this.GetType(),"alert", message.ToString());
        }
    }

    protected void ab_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        ab.EditIndex = -1;
        LoadGrid();

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
            DataTable DT = new DataTable();
       int aa= Convert.ToInt32(A1.Text.ToString());
       string bb = A2.Text.ToString();
       string cc = A3.Text.ToString();
       int dd = Convert.ToInt32(A4.Text.ToString());
            Response.Write("<script>alert('Insert failed');</script>");
            myDAL objMyDal = new myDAL();
        objMyDal.insertItem(aa,bb,cc,dd,ref DT);
        LoadGrid();
    }
    }
}

dal文件中的定義如下

public int insertItem(int reg, string name, string add, int o1, ref DataTable DT)
    {
        DataSet ds = new DataSet();
        SqlConnection con = new SqlConnection(connString);
        con.Open();
        SqlCommand cmd,cmd1;
        int result = 0;
        try
        {
            //cmd1 = new SqlCommand("newNGO", con);
            cmd = new SqlCommand("insert into NGO values (@reg_no,@nname,@address,@owner_id)", con);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@reg_no", SqlDbType.Int).Value = reg;
            cmd.Parameters.Add("@nname", SqlDbType.VarChar).Value = name;
            cmd.Parameters.Add("@address", SqlDbType.VarChar).Value = add;
            cmd.Parameters.Add("@owner_id", SqlDbType.Int).Value = o1;
            /*

            cmd1.Parameters.Add("@nname", SqlDbType.VarChar).Value = name;
            cmd1.Parameters.Add("@address", SqlDbType.VarChar).Value = add;
            cmd1.Parameters.Add("@owner_id", SqlDbType.Int).Value = o1;
            */
            result = cmd.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            Console.WriteLine("SQL Error" + ex.Message.ToString());
        }
        finally
        {
            con.Close();
        }

        return result;
    }

表的列名是 reg_no (int)、nname(varchar)、address(varchar) 和 owner_id(int)。 reg_no 是主鍵,owner_id 是外鍵。 自上周以來,我一直在試圖找出錯誤。 單擊插入按鈕不會引發任何異常或錯誤,但也不會在數據庫中插入值。

將 cmd.Parameters.Add 更改為 cmd.Parameters.AddWithValue 然后嘗試

我想我已經想通了。 變量 nname 被設置為 varchar(20) 並且我正在輸入一個字符串“Doctors without Borders”,它顯然大於 20,因此它拋出了異常。 感謝您的幫助和關注。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM