datagrid中添加一个空行,然后设置该行的状态为编辑状态

解决方案 »

  1.   

    datagrid中添加一个空行,那这样的话,更新数据库还要不要写语句更新,谢谢
      

  2.   

    // TODO: update the ConnectionString and Command values for your applicationstring ConnectionString = "server=(local);database=pubs;trusted_connection=true";
    string SelectCommand = "SELECT au_id, au_lname, au_fname from Authors";bool isEditing = false;void Page_Load(object sender, EventArgs e) {    if (!Page.IsPostBack) {        // Databind the data grid on the first request only
            // (on postback, bind only in editing, paging and sorting commands)        BindGrid();
        }
    }// ---------------------------------------------------------------
    //
    // DataGrid Commands: Page, Sort, Edit, Update, Cancel, Delete
    //void DataGrid_ItemCommand(object sender, DataGridCommandEventArgs e) {    // this event fires prior to all of the other commands
        // use it to provide a more graceful transition out of edit mode    CheckIsEditing(e.CommandName);
    }void CheckIsEditing(string commandName) {    if (dgUserInfo.EditItemIndex != -1) {        // we are currently editing a row
            if (commandName != "Cancel" && commandName != "Update") {            // user's edit changes (if any) will not be committed
                Message.Text = "Your changes have not been saved yet.  Please press update to save your changes, or cancel to discard your changes, before selecting another item.";
                isEditing = true;
            }
        }
    }void DataGrid_Edit(object sender, DataGridCommandEventArgs e) {    // turn on editing for the selected row    if (!isEditing) {
            dgUserInfo.EditItemIndex = e.Item.ItemIndex;
            BindGrid();
        }
    }void DataGrid_Update(object sender, DataGridCommandEventArgs e) {    // update the database with the new values    // get the edit text boxes
        string id = ((TextBox)e.Item.Cells[2].Controls[0]).Text;
        string lname = ((TextBox)e.Item.Cells[3].Controls[0]).Text;
        string fname = ((TextBox)e.Item.Cells[4].Controls[0]).Text;    // TODO: update the Command value for your application
        SqlConnection myConnection = new SqlConnection(ConnectionString);
        SqlCommand UpdateCommand = new SqlCommand();
        UpdateCommand.Connection = myConnection;    if (AddingNew)
            UpdateCommand.CommandText = "INSERT INTO authors(au_id, au_lname, au_fname, contract) VALUES (@au_id, @au_lname, @au_fname, 0)";
        else
            UpdateCommand.CommandText = "UPDATE authors SET au_lname = @au_lname, au_fname = @au_fname WHERE au_id = @au_id";    UpdateCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11).Value = id;
        UpdateCommand.Parameters.Add("@au_lname", SqlDbType.VarChar, 40).Value = lname;
        UpdateCommand.Parameters.Add("@au_fname", SqlDbType.VarChar, 20).Value = fname;    // execute the command
        try {
            myConnection.Open();
            UpdateCommand.ExecuteNonQuery();
        }
        catch (Exception ex) {
            Message.Text = ex.ToString();
        }
        finally {
            myConnection.Close();
        }    // Resort the grid for new records
        if (AddingNew) {        dgUserInfo.CurrentPageIndex = 0;
            AddingNew = false;
        }    // rebind the grid
        dgUserInfo.EditItemIndex = -1;
        BindGrid();
    }void DataGrid_Cancel(object sender, DataGridCommandEventArgs e) {    // cancel editing    dgUserInfo.EditItemIndex = -1;
        BindGrid();    AddingNew = false;
    }void DataGrid_Delete(object sender, DataGridCommandEventArgs e) {    // delete the selected row    if (!isEditing) {        // the key value for this row is in the DataKeys collection
            string keyValue = (string)dgUserInfo.DataKeys[e.Item.ItemIndex];        // TODO: update the Command value for your application
            SqlConnection myConnection = new SqlConnection(ConnectionString);
            SqlCommand DeleteCommand = new SqlCommand("DELETE from authors where au_id='" + keyValue + "'", myConnection);        // execute the command
            myConnection.Open();
            DeleteCommand.ExecuteNonQuery();
            myConnection.Close();        // rebind the grid
            dgUserInfo.CurrentPageIndex = 0;
            dgUserInfo.EditItemIndex = -1;
            BindGrid();
        }
    }void DataGrid_Page(object sender, DataGridPageChangedEventArgs e) {    // display a new page of data    if (!isEditing) {
            dgUserInfo.EditItemIndex = -1;
            dgUserInfo.CurrentPageIndex = e.NewPageIndex;
            BindGrid();
        }
    }void AddNew_Click(Object sender, EventArgs e) {    // add a new row to the end of the data, and set editing mode 'on'    CheckIsEditing("");    if (!isEditing) {        // set the flag so we know to do an insert at Update time
            AddingNew = true;        // add new row to the end of the dataset after binding        // first get the data
            SqlConnection myConnection = new SqlConnection(ConnectionString);
            SqlDataAdapter myCommand = new SqlDataAdapter(SelectCommand, myConnection);        DataSet ds = new DataSet();
            myCommand.Fill(ds);        // add a new blank row to the end of the data
            object[] rowValues = { "", "", "" };
            ds.Tables[0].Rows.Add(rowValues);        // figure out the EditItemIndex, last record on last page
            int recordCount = ds.Tables[0].Rows.Count;
            if (recordCount > 1)
                recordCount--;
            dgUserInfo.CurrentPageIndex = recordCount/dgUserInfo.PageSize;
            dgUserInfo.EditItemIndex = recordCount%dgUserInfo.PageSize;        // databind
            dgUserInfo.DataSource = ds;
            dgUserInfo.DataBind();
        }
    }// ---------------------------------------------------------------
    //
    // Helpers Methods:
    //// property to keep track of whether we are adding a new record,
    // and save it in viewstate between postbacksprotected bool AddingNew {    get {
            object o = ViewState["AddingNew"];
            return (o == null) ? false : (bool)o;
        }
        set {
            ViewState["AddingNew"] = value;
        }
    }void BindGrid() {    SqlConnection myConnection = new SqlConnection(ConnectionString);
        SqlDataAdapter myCommand = new SqlDataAdapter(SelectCommand, myConnection);    DataSet ds = new DataSet();
        myCommand.Fill(ds);    dgUserInfo.DataSource = ds;
        dgUserInfo.DataBind();
    }
      

  3.   

    直接用 Adapter.update(DataTable)的话就不用写插入语句了。
      

  4.   

    <html>
    <head>
    </head>
    <body style="FONT-FAMILY: arial">
        <h2>Editable Data Grid 
        </h2>
        <hr size="1" />
        <form runat="server">
            <asp:datagrid id="dgUserInfo" runat="server" DataKeyField="au_id" OnItemCommand="DataGrid_ItemCommand" OnEditCommand="DataGrid_Edit" OnUpdateCommand="DataGrid_Update" OnCancelCommand="DataGrid_Cancel" OnDeleteCommand="DataGrid_Delete" AllowPaging="true" PageSize="6" OnPageIndexChanged="DataGrid_Page" ForeColor="Black" BackColor="White" CellPadding="3" GridLines="None" CellSpacing="1" width="80%">
                <FooterStyle backcolor="#C6C3C6"></FooterStyle>
                <HeaderStyle font-bold="True" forecolor="White" backcolor="#4A3C8C"></HeaderStyle>
                <PagerStyle font-size="Smaller" horizontalalign="Right" backcolor="#C6C3C6" mode="NumericPages"></PagerStyle>
                <ItemStyle backcolor="#DEDFDE"></ItemStyle>
                <Columns>
                    <asp:EditCommandColumn ButtonType="LinkButton" UpdateText="Update" CancelText="Cancel" EditText="Edit">
                        <ItemStyle font-size="Smaller" width="10%"></ItemStyle>
                    </asp:EditCommandColumn>
                    <asp:ButtonColumn Text="Delete" CommandName="Delete">
                        <ItemStyle font-size="Smaller" width="10%"></ItemStyle>
                    </asp:ButtonColumn>
                </Columns>
            </asp:datagrid>
            <br />
            <asp:LinkButton id="LinkButton1" onclick="AddNew_Click" runat="server" Text="Add new item" Font-Size="smaller"></asp:LinkButton>
            <br />
            <br />
            <asp:Label id="Message" runat="server" width="80%" forecolor="red" enableviewstate="false"></asp:Label>
        </form>
    </body>
    </html>
      

  5.   

    直接在DataGrid的每一行的Footer中添加一个TextBox设置Footer为不可视,电击按钮后再作设置Footer为可视,添加数据保存后,判断是否继续添加 yes 依然可视保持在添加]状态, no不可视.
      

  6.   

    好像各位讲的跟我的想法不符合,其实,我的问题很简单,就是说窗体上只有一个工具栏和一个grid,新增,删除这些按纽在工具栏上,那每次新增数据时,当我按下新增后,grid就要自动空出一行,让用户输入数据,然后存盘.我就是不知道用什么命令,grid会空出一行?
      

  7.   

    我也很关注这个问题》
    jsp  中用js 能实现 
    可是datagird  想知道?
    UP
      

  8.   

    好了,謝謝各位了,我明白了,grid在new row后會空出一行,不過是在最后,並不是在當前的指針處