Frage

I'm trying to create my new asp.net website using npgsql. My database looks like this:

[oid, countyname, status]

Using npgsql I've already connected and displayed data in gridview. I've done this using this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Npgsql;
using System.Data;
using System.Web.Security;


public partial class Secured_pia : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {         
        string sQuery = "SELECT countyname, status FROM countydb";
        string sConn = "Server=localhost;Port=5432;User Id=user1;Password=pass2;Database=database;";

        DataTable DT = new DataTable();
        NpgsqlConnection Conn = new NpgsqlConnection(sConn);

        Conn.Open();

        DataSet DS = new DataSet("DS1");
        NpgsqlDataAdapter DA = new NpgsqlDataAdapter();

        DA.SelectCommand = new NpgsqlCommand(sQuery, Conn);

        DA.Fill(DS, "DS1");

        GridView1.DataSource = DS;
        GridView1.DataBind();

        Conn.Close();
    }
}

Everything works fine. Now I want to edit that table. As I've read good, I can use NpgsqlCommandBuilder to make insert, update and delete commands. So I changed the code to like this:

DA.SelectCommand = new NpgsqlCommand(sQuery, Conn);
NpgsqlCommandBuilder UpdateCMD = new NpgsqlCommandBuilder(DA);         
DA.Fill(DS, "DS1");

And now, I don't know what should I do to turn on editing. Is that code enough to turn on editing in gridview? My aspx code looks like this:

<asp:GridView ID="GridView1" runat="server">
    <Columns>
        <asp:CommandField ShowEditButton="true" />
    </Columns>
</asp:GridView>

Is aspx.cs code good? Do I have to add any properties to my gridview? Thanks for replies, and sorry for my simple questions. I'm new in this.

War es hilfreich?

Lösung

I would just add a button on the page next to the gridview. Then implement your update button click event like this:

 public partial class Secured_pia : System.Web.UI.Page
    {
        String sConn = "Your connection string";
        private NpgsqlConnection conn;
        private NpgsqlDataAdapter da;
        private DataSet ds = new DataSet();
        private DataTable dt = new DataTable();
        private NpgsqlCommandBuilder cb;

        public Secured_pia ()
        {
            InitializeComponent();
        }
//your form load code above goes here but you will have to do 
//a global declaration like I did here instead of in the form load event like you have. 

//update button implementation.  
private void btnUpdate_Click(object sender, EventArgs e)
 {
    cb = new NpgsqlCommandBuilder(da);           
    da.Update(dt);
 }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top