Gridview页脚不是实例

时间:2018-04-12 20:13:12

标签: c# gridview footer

我试图为gridview页脚文本框获取自动ID填充,但每次运行时我都会获得对象的" Not Referred Instance"意思是方法找不到文本框,对吧? 但我在其他方法中有相同的文本框,并且工作正常,它有什么不对?

以下是GridView的代码示例

   <asp:GridView ID="GridView1" runat="server" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" AutoGenerateColumns="False" ShowFooter="True">
            <Columns>
                <asp:TemplateField HeaderText="ID UNIDAD">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ID_UNIDAD") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtAddID" runat="server" ></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lbl_ID" runat="server" Text='<%# Bind("ID_UNIDAD") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="UNIDAD">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("NOMBRE") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtNombre" runat="server" ></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lbl_Nombre" runat="server" Text='<%# Bind("NOMBRE") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                   <asp:TemplateField HeaderText="FRACCIONES">
                    <EditItemTemplate>
                        <asp:CheckBox ID="TextBox3" runat="server" Checked='<%# Bind("FRACCIONES") %>'></asp:CheckBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:CheckBox ID="chkFraccion" runat="server" ></asp:CheckBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="lbl_Fraccion" runat="server" Checked='<%# Bind("FRACCIONES") %>' ></asp:CheckBox>
                    </ItemTemplate>
                </asp:TemplateField>
                   <asp:TemplateField HeaderText="CLAVE SAT">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("CLAVE_SAT") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtClave" runat="server" ></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lbl_Clave" runat="server" Text='<%# Bind("CLAVE_SAT") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <FooterTemplate>
                        <asp:ImageButton ID="Agregar" runat="server" ImageUrl="~/assets/iconos/add.ico" OnClick="Agregar_Click" />       
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#CCCCCC" />
            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
            <RowStyle BackColor="White" />
            <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#808080" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#383838" />
        </asp:GridView> 

以下是在

后面的代码中绑定网格的代码示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Windows.Input;


public partial class Default2 : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Integral Database"].ToString());
    string query;
    string countid = " ";
    SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["Integral Database"].ToString());
    string connStrr = ConfigurationManager.ConnectionStrings["Integral Database"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)

            llenagrid();
        IncrementoID();
    }



    public void llenagrid()
    {
      DataTable table = new DataTable();
      using (SqlConnection conn = new SqlConnection(connStrr))
      {
          string sql = "SELECT id_unidad, nombre, fracciones, clave_sat from unidades";
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
                {
                    ad.Fill(table);
                }
           }
       }
      IncrementoID();
  GridView1.DataSource = table;
  GridView1.DataBind();        
    }



    protected void Agregar_Click(object sender, ImageClickEventArgs e)
    {
        connStr.Open();
        GridViewRow row = GridView1.FooterRow;
        TextBox txtNombre = (TextBox)row.FindControl("txtNombre");
        string str = "select count(nombre) from unidades where nombre like '"+txtNombre.Text+ "'";
        SqlCommand com = new SqlCommand(str,connStr);
        int count = Convert.ToInt32(com.ExecuteScalar());
        connStr.Close();
        if (count > 0)
        {
            string script = "alert('Este Nombre ya Existe.','Atención');";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "testScript", script, true);
        }
        else
        {
            connStr.Open();
            TextBox txtID = (TextBox)row.FindControl("txtAddID");
            CheckBox chkFracc = (CheckBox)row.FindControl("chkFraccion");
            TextBox txtClave = (TextBox)row.FindControl("txtClave");
            string ID = txtID.Text;
            string Nombre = txtNombre.Text;
            bool Fracc = chkFracc.Checked;
            string clave = txtClave.Text;
            string query2 = "Insert into unidades values('" + ID + "','" + Nombre + "','" + Fracc + "','" + clave + "')";
            SqlCommand cmd2 = new SqlCommand(query2, connStr);
            cmd2.ExecuteNonQuery();
            connStr.Close();
            llenagrid();
            IncrementoID();
        }

     }


    public void IncrementoID()
    {
        //query = "select Count(id_unidad) from unidades";
        //con.Open();
        //SqlCommand cmd = new SqlCommand(query, con);
        //string cid = cmd.ExecuteScalar().ToString();
        //con.Close();
        //TextBox ID = (TextBox)GridView1.FooterRow.FindControl("txtAddID");
        //ID.Text = countid + (int.Parse(cid) + 1);
        //ID.ReadOnly = true;

        con.Open();
        SqlCommand cmd = new SqlCommand("select MAX (CAST( ID_UNIDAD as INT)) from unidades",con);
        SqlDataReader rd = cmd.ExecuteReader();
        TextBox txtID = ((TextBox)GridView1.FooterRow.FindControl("txtAddID"));
        if (rd.Read())
        {
            string Value = rd[0].ToString();
            if (Value == "")
            {

                txtID.Text = "1";
            }
            else
            {
                txtID.Text = rd[0].ToString();
                txtID.Text = (Convert.ToInt64(txtID.Text) + 1).ToString();
            }
        }
        con.Close();
    }

    }

正如您所看到的,在insert方法中它找到了gridview文本框(txtAddID),当我尝试在IncrementoID方法中使用相同的语法时,它不起作用。

1 个答案:

答案 0 :(得分:0)

以下是方法llenagrid()中的问题,在绑定GridView之前,您试图访问Gridview中的控件(在方法IncrementoID内),所以它给出错误 Not Referred对象的实例表示尚未引用您尝试访问的对象。下面的代码示例可以帮助您:

public void llenagrid()
  {
          DataTable table = new DataTable();
          using (SqlConnection conn = new SqlConnection(connStrr))
          {
              string sql = "SELECT id_unidad, nombre, fracciones, clave_sat from unidades";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
                    {
                        ad.Fill(table);
                    }
               }
           }
      //IncrementoID(); // Remove the function call from here
      GridView1.DataSource = table;
      GridView1.DataBind(); 
      IncrementoID();  // Call the function after GridView got binded.      
   }