简体   繁体   中英

How to bind GridView to the Database and perform Update/Insert operations

I am using asp.net 4.0 C# and Sql server 2008r2.

I have found and using code from here to create my gridview with textboxes and from here to save to my database with a slight modification as seen below.

I need to recall that data from the database and populate the dynamicly created textboxes in the gridview.

I am receiveing an error "A field or property wht the name 'RowNumber' was not found on the selected data souce." The error is on the line Gridview.DataBind(); in the Fillmygrid method.

How do I get the row to incrament for each line returned. This column is not in the database.

My current code is:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            SetInitialRow();
            querytable();
        }
    }
    protected void querytable()
    {
        string id = Session["ID"] as string;
        using (SqlConnection con = new SqlConnection(connection string))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM table WHERE column1 = @c1 AND column3 = 'A'", con))
            cmd.Parameters.AddWithValue("@c1", id);
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.hasRows)
            {
                FillGrid();
            }
         }
      }
   }
    private void AddNewRowToGrid()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;
                    dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                    rowIndex++;
                }
                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;

                Gridview1.DataSource = dtCurrentTable;
                Gridview1.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }
        SetPreviousData();
    }

    private void SetPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                    box1.Text = dt.Rows[i]["Column1"].ToString();
                    rowIndex++;
                }
            }
        }
    }
    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        AddNewRowToGrid();
    }

    private void SetInitialRow()
    {
    DataTable dt = new DataTable();
    DataRow dr = null;
    dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
    dt.Columns.Add(new DataColumn("Column1", typeof(string)));
    dr = dt.NewRow();
    dr["RowNumber"] = 1;
    dr["Column1"] = string.Empty;
    dt.Rows.Add(dr);
    dr = dt.NewRow();
    ViewState["CurrentTable"] = dt;

    Gridview1.DataSource = dt;
    Gridview1.DataBind();
    }


    private void InsertRecords(StringCollection sc)
    {
        SqlConnection conn = new SqlConnection(GetConnectionString());
        StringBuilder sb = new StringBuilder(string.Empty);
        string[] splitItems = null;
        foreach (string item in sc)
        {

            const string sqlStatement = "INSERT INTO SampleTable (Column1,Column2,Column3) VALUES";
            if (item.Contains(","))
            {
                splitItems = item.Split(",".ToCharArray());
                sb.AppendFormat("{0}('{1}','{2}','{3}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2]);
            }

        }

        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();

            Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);

        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);

        }
        finally
        {
            conn.Close();
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string id = Session["ID"] as string;
        int rowIndex = 0;
        StringCollection sc = new StringCollection();
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1"); 
                string a = "A"
                sc.Add(id + "," + box1.Text + "," + a);
                rowIndex++;
                }
                InsertRecords(sc);
            }
        }
    }

Here is the problem code: Change 2 to this code:

    private void fillmygrid()
    {
        string id = Session["ID"] as string;
        //DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection(connection string)
        try
        {
            string cmd "Select column2 From table where column1 = '@c1' And  column3 = 'A'";
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd, con);
            da.SelectCommand.Parameters.AddWithValue("@c1", id);
            DataSet ds = new DataSet();
            da.Fill(ds);
            if (dt.Rows.Count > 0)
            {
                Gridview1.DataSource = dt;
                Gridview1.DataBind();
            }
        }
        catch (SqlException ex)
        {
            string msg = "Fetch Error:";
            msg += ex.Message;
            Response.Write(msg);
        }
        finally
        {
            con.Close();
        }
    }

My insert statement works and I am linking to the same connection string.

Thanks for your help.

Use a standardized approach, namely SqlDataSource bind to GridView control (ASP.NET). There are plenty of samples online, eg http://asp-net-example.blogspot.com/2008/12/aspnet-gridview-and-sqldatasource.html This solution will allow you to SELECT, DELETE or UPDATE the Data Table in your SQL Database.

In order To ADD (ie INSERT) new record, use FormView (if necessary). Regards,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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