简体   繁体   English

使用 asp.net 和 C# 将数据插入 gridview

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

I have recently been involved in a mini-project and am trying to use asp.net with SQL in it.我最近参与了一个小型项目,并尝试在其中使用带有 SQL 的 asp.net。 The problem I am facing is that the insert function is not working although the edit and delete are working perfectly fine on the same page.我面临的问题是插入功能不起作用,尽管编辑和删除在同一页面上工作得很好。 This is the home2.aspx file这是 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>

This is the aspx.cs file这是 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();
    }
    }
}

The definition in the dal file is as follows 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;
    }

The column names of the table are reg_no (int), nname(varchar), address(varchar) and owner_id(int).表的列名是 reg_no (int)、nname(varchar)、address(varchar) 和 owner_id(int)。 reg_no is the primary key and owner_id is foreign key. reg_no 是主键,owner_id 是外键。 I have been trying to find out the error since last week.自上周以来,我一直在试图找出错误。 Clicking the insert button does not throw any exception or error but it also does not insert the values in the database.单击插入按钮不会引发任何异常或错误,但也不会在数据库中插入值。

将 cmd.Parameters.Add 更改为 cmd.Parameters.AddWithValue 然后尝试

I think I have figured it out.我想我已经想通了。 The variable nname was set as varchar(20) and I was entering a string "Doctors without Borders" which is clearly larger than 20 and therefore it was throwing the exception.变量 nname 被设置为 varchar(20) 并且我正在输入一个字符串“Doctors without Borders”,它显然大于 20,因此它抛出了异常。 Thanks for your help and concerns.感谢您的帮助和关注。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM