locked
empty row at the end of dataGridView RRS feed

  • Question

  • Hi,

    I bind a dataGridView like below

     private void Form1_Load(object sender, EventArgs e)
            {
                SqlDataReader dr = mydalbase.ExecuteReader(System.Data.CommandType.StoredProcedure, "spGetAllContacts", new SqlParameter[]{
                });
                
                BindingSource BindingSource1 = new BindingSource();
                BindingSource1.DataSource = dr;
                dataGridView1.DataSource = BindingSource1;

    and the Allowusertoaddrows is true

    I need an empty row at the end of datagridview,can I have it when I bind contol programmatically?

    If no I have another question

    when I bind control with wizard there is a blank row at the end but only the id column isn't empty

    but i want id column be empty too.

    the id column in database is identity

    thanks

    Friday, May 31, 2013 9:07 AM

Answers

  • Hello,

    A work-around (since you are hitting default behavior) would be to handle the AddingNew event of your BindingSource.

    Example shown in VB.NET and will work in C# where (optional) I set a default value for a column and also set the fore color of the primary key column to white. The downside here is if the primary key column is selected they will see the value from the highlight but most people are not going to do this.

    Private Sub BindingSource1_AddingNew(
        ByVal sender As Object,
        ByVal e As System.ComponentModel.AddingNewEventArgs) _
    Handles BindingSource1.AddingNew
        Dim dv As DataView = TryCast(BindingSource1.List, DataView)
        Dim drv As DataRowView = dv.AddNew()
        drv("CompanyName") = "Enter a name"
        e.NewObject = drv
        BindingSource1.MoveLast()
        DataGridView1.Rows(BindingSource1.Position).Cells("IdentiferColumn").Style.ForeColor = Color.White
    End Sub

    When they save we would do something like this.

    Private Sub BindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BindingNavigatorSaveItem.Click
        Me.Validate()
        Me.BindingSource1.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.Database1DataSet)
        DataGridView1.Rows(BindingSource1.Count - 1).Cells("IdentiferColumn").Style.ForeColor = Nothing
    End Sub
    Now if the person added more than one row then saved you would want to loop thru all new rows in the DataGridView or simply loop thru all rows and set the fore color.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

    • Marked as answer by Barry Wang Friday, June 7, 2013 9:18 AM
    Sunday, June 2, 2013 10:12 PM