Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I prevent a DataGrid from allowing new rows to be added, and so suppress display of the append row (i.e., the row at the end with an asterisk)?

The DataGrid class does not have a property that controls whether a new row can be added. But the DataView class does have such an AllowNew property (among others such as AllowEdit and AllowDelete). Here is code that will turn off the append row by getting the DataView associated with the DataGrid and setting its AllowNew property to false.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

// ...
private const string connectionString =
  "Integrated Security=SSPI;Initial Catalog=Northwind;Data Source=(local);";
private const string commandText = "SELECT * FROM Customers";
// ...

private void Form1_Load(object sender, EventArgs e)
{
  // create data source
  DataSet dataSet = new DataSet();
  using ( SqlDataAdapter adapter =
            new SqlDataAdapter( commandText, connectionString ) )
    adapter.Fill( dataSet );

  // bind DataGrid to data source, and disallow adding a new row
  dataGrid1.DataSource = dataSet.Tables[ 0 ];
  DisallowNewRow( dataGrid1 );
}

// disallow adding a new row (suppresses append row at end of DataGrid)
private void DisallowNewRow( DataGrid dataGrid )
{
  CurrencyManager cm =
    (CurrencyManager) BindingContext[ dataGrid1.DataSource ];
  DataView dataView = (DataView) cm.List;
  dataView.AllowNew = false;
}

If the DataGrid contains links, add a Navigate handler that disallows the AllowNew, as shown below.

private void DataGrid1_Navigate( object sender, NavigateEventArgs ne )
{
  if ( ne.Forward ) DisallowNewRow( dataGrid1 );
}

George Shepherd, Syncfusion, and Matthew Miller



Page view counter