DataRow.Item[] Propriedade

Definição

Obtém ou define dados armazenados numa coluna especificada.

Sobrecargas

Name Description
Item[DataColumn]

Obtém ou define os dados armazenados no especificado DataColumn.

Item[Int32]

Obtém ou define os dados armazenados na coluna especificada pelo índice.

Item[String]

Obtém ou define os dados armazenados na coluna especificada pelo nome.

Item[DataColumn, DataRowVersion]

Obtém a versão especificada dos dados armazenada no .DataColumn

Item[Int32, DataRowVersion]

Obtém os dados armazenados na coluna, especificados pelo índice e versão dos dados a recuperar.

Item[String, DataRowVersion]

Obtém a versão especificada dos dados armazenada na coluna nomeada.

Item[DataColumn]

Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs

Obtém ou define os dados armazenados no especificado DataColumn.

public:
 property System::Object ^ default[System::Data::DataColumn ^] { System::Object ^ get(System::Data::DataColumn ^ column); void set(System::Data::DataColumn ^ column, System::Object ^ value); };
public object this[System.Data.DataColumn column] { get; set; }
member this.Item(System.Data.DataColumn) : obj with get, set
Default Public Property Item(column As DataColumn) As Object

Parâmetros

column
DataColumn

A DataColumn que contém os dados.

Valor de Propriedade

E Object que contém os dados.

Exceções

A coluna não pertence a esta tabela.

O column é nulo.

Foi feita uma tentativa de definir um valor numa linha eliminada.

Os tipos de dados do valor e da coluna não coincidem.

Exemplos

Os exemplos seguintes demonstram a utilização da Item[] propriedade para obter e definir o valor de um índice de colunas específico. O primeiro exemplo recebe o valor da primeira coluna em qualquer linha em que o utilizador clique num DataGrid controlo. A segunda define um valor passado como argumento ao método.

Private Sub DataGrid1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs)
    
    Dim dataGridTable As DataTable = _
        CType(DataGrid1.DataSource, DataTable)
    ' Set the current row using the RowNumber 
    ' property of the CurrentCell.
    Dim currentRow As DataRow = _
        dataGridTable.Rows(DataGrid1.CurrentCell.RowNumber)
    Dim column As DataColumn = dataGridTable.Columns(1)

    ' Get the value of the column 1 in the DataTable.
    label1.Text = currentRow(column).ToString()
End Sub
 
Private Sub SetDataRowValue( _
    ByVal grid As DataGrid, ByVal newVal As Object)

    ' Set the value of a column in the last row of a DataGrid.
    Dim table As DataTable = CType(grid.DataSource, DataTable)
    Dim row As DataRow = table.Rows(table.Rows.Count - 1)
    Dim column As DataColumn = table.Columns("FirstName")
    row(column)= newVal
End Sub

Observações

Quando define a propriedade, é gerada uma exceção se esta ocorrer no ColumnChanging evento.

Se esta for uma edição imediata, veja EndEdit as exceções que podem ser geradas.

Aplica-se a

Item[Int32]

Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs

Obtém ou define os dados armazenados na coluna especificada pelo índice.

public:
 property System::Object ^ default[int] { System::Object ^ get(int columnIndex); void set(int columnIndex, System::Object ^ value); };
public object this[int columnIndex] { get; set; }
member this.Item(int) : obj with get, set
Default Public Property Item(columnIndex As Integer) As Object

Parâmetros

columnIndex
Int32

O índice zero da coluna.

Valor de Propriedade

E Object que contém os dados.

Exceções

Acontece quando tentas definir um valor numa linha eliminada.

O columnIndex argumento está fora de alcance.

Ocorre quando defines o valor e o Type novo valor não coincide DataType.

Exemplos

Os exemplos seguintes demonstram a utilização da Item[] propriedade para obter e definir o valor de um índice de colunas específico. O primeiro exemplo recebe o valor da primeira coluna em qualquer linha em que o utilizador clique num DataGrid controlo.

private void DataGrid1_Click(object sender,
    System.EventArgs e)
{
    // Get the DataTable the grid is bound to.
    DataGrid thisGrid = (DataGrid) sender;
    DataTable table = (DataTable) thisGrid.DataSource;
    DataRow currentRow =
        table.Rows[thisGrid.CurrentCell.RowNumber];

    // Get the value of the column 1 in the DataTable.
    Console.WriteLine(currentRow[1]);
    // You can also use the name of the column:
    // Console.WriteLine(currentRow["FirstName"])
}

private void SetDataRowValue(DataGrid grid, object newValue)
{
    // Set the value of the last column in the last row of a DataGrid.
    DataTable table;
    table = (DataTable) grid.DataSource;
    DataRow row;

    // Get last row
    row = (DataRow)table.Rows[table.Rows.Count-1];

    // Set value of last column
    row[table.Columns.Count-1] = newValue;
}
Private Sub DataGrid1_Click _
    (ByVal sender As System.Object, ByVal e As System.EventArgs)

    ' Get the DataTable the grid is bound to.
    Dim thisGrid As DataGrid = CType(sender, DataGrid)
    Dim table As DataTable = CType(thisGrid.DataSource, DataTable)
    Dim currentRow As DataRow = _
        table.Rows(thisGrid.CurrentCell.RowNumber)

    ' Get the value of the column 1 in the DataTable.
    Console.WriteLine(currentRow(1))
    ' You can also use the name of the column:
    ' Console.WriteLine(currentRow("FirstName"))
    End Sub

    Private Sub SetDataRowValue( _
        ByVal grid As DataGrid, ByVal newValue As Object)

    ' Set the value of the last column in the last row of a DataGrid.
    Dim table As DataTable
    table = CType(grid.DataSource, DataTable)
    Dim row As DataRow 
    row = table.Rows(table.Rows.Count-1)
    row(table.Columns.Count-1) = newValue
End Sub

Observações

Quando define a propriedade, é gerada uma exceção se esta ocorrer no ColumnChanging evento.

Se isto for uma edição, veja EndEdit as exceções que podem ser geradas.

Aplica-se a

Item[String]

Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs

Obtém ou define os dados armazenados na coluna especificada pelo nome.

public:
 property System::Object ^ default[System::String ^] { System::Object ^ get(System::String ^ columnName); void set(System::String ^ columnName, System::Object ^ value); };
public object this[string columnName] { get; set; }
member this.Item(string) : obj with get, set
Default Public Property Item(columnName As String) As Object

Parâmetros

columnName
String

O nome da coluna.

Valor de Propriedade

E Object que contém os dados.

Exceções

A coluna especificada por columnName não pode ser encontrada.

Acontece quando tentas definir um valor numa linha eliminada.

Ocorre quando defines um valor e este Type não corresponde DataTypea .

Ocorre quando tenta inserir um valor nulo numa coluna onde AllowDBNull está definido como false.

Exemplos

Os exemplos seguintes demonstram a utilização da Item[] propriedade para obter e definir o valor de um índice de colunas específico. O primeiro exemplo recebe o valor da primeira coluna em qualquer linha em que o utilizador clique num DataGrid controlo. A segunda define um valor passado como argumento ao método.

private void DataGrid1_Click(
    object sender, System.EventArgs e)
{
    // Get the DataTable the grid is bound to.
    DataGrid thisGrid = (DataGrid) sender;
    DataTable table = (DataTable) thisGrid.DataSource;
    DataRow currentRow =
        table.Rows[thisGrid.CurrentCell.RowNumber];

    // Get the value of the column 1 in the DataTable.
    Console.WriteLine(currentRow["FirstName"]);
    // You can also use the index:
    // Console.WriteLine(currentRow[1]);
}

private void SetDataRowValue(
    DataGrid grid, object newValue)
{
    // Set the value of the first column in
    // the last row of a DataGrid.
    DataTable table = (DataTable) grid.DataSource;
    DataRow row = table.Rows[table.Rows.Count-1];
    row["FirstName"] = newValue;
}
Private Sub DataGrid1_Click( _
    sender As Object, e As System.EventArgs)
     
    ' Get the DataTable the grid is bound to.
    Dim thisGrid As DataGrid = CType(sender, DataGrid)
    Dim table As DataTable = _
        CType(thisGrid.DataSource, DataTable)
    Dim currentRow As DataRow = _
        table.Rows(thisGrid.CurrentCell.RowNumber)

    ' Get the value of the column 1 in the DataTable.
    Console.WriteLine(currentRow("FirstName"))
    ' You can also use the index:
    ' Console.WriteLine(currentRow(1).ToString())
End Sub
    
Private Sub SetDataRowValue( _
    grid As DataGrid, newValue As Object)
    ' Set the value of the first column in 
    ' the last row of a DataGrid.
    Dim table As DataTable = _
        CType(grid.DataSource, DataTable)
    Dim row As DataRow
    row = table.Rows((table.Rows.Count - 1))
    row("FirstName") = newValue
End Sub

Observações

Quando define a propriedade, é gerada uma exceção se esta ocorrer no ColumnChanging evento.

Se esta for uma edição imediata, veja EndEdit as exceções que podem ser geradas.

Aplica-se a

Item[DataColumn, DataRowVersion]

Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs

Obtém a versão especificada dos dados armazenada no .DataColumn

public:
 property System::Object ^ default[System::Data::DataColumn ^, System::Data::DataRowVersion] { System::Object ^ get(System::Data::DataColumn ^ column, System::Data::DataRowVersion version); };
public object this[System.Data.DataColumn column, System.Data.DataRowVersion version] { get; }
member this.Item(System.Data.DataColumn * System.Data.DataRowVersion) : obj
Default Public ReadOnly Property Item(column As DataColumn, version As DataRowVersion) As Object

Parâmetros

column
DataColumn

A DataColumn que contém informações sobre a coluna.

version
DataRowVersion

Um dos DataRowVersion valores que especifica a versão da linha que queres. Os valores possíveis são Default, Original, Current, e Proposed.

Valor de Propriedade

E Object que contém os dados.

Exceções

A coluna não pertence à tabela.

O column argumento contém nulo.

A linha não tem esta versão dos dados.

Exemplos

O exemplo seguinte obtém o valor atual de uma célula clicada no DataGrid controlo.

private void DataGrid1_Click(object sender,
    System.EventArgs e)
{
    DataTable dataGridTable =
        (DataTable)DataGrid1.DataSource;

    // Set the current row using the RowNumber
    // property of the CurrentCell.
    DataRow currentRow = dataGridTable.Rows[DataGrid1.CurrentCell.RowNumber];
    DataColumn column = dataGridTable.Columns[1];

    // Get the value of the column 1 in the DataTable.
    Console.WriteLine(currentRow[column, DataRowVersion.Current]);
}
Private Sub DataGrid1_Click _
    (ByVal sender As System.Object, ByVal e As System.EventArgs)

    Dim dataGridTable As DataTable = _
        CType(DataGrid1.DataSource, DataTable)

    ' Set the current row using the RowNumber 
    ' property of the CurrentCell.
    Dim currentRow As DataRow = dataGridTable.Rows( _
        DataGrid1.CurrentRowIndex)
    Dim column As DataColumn = dataGridTable.Columns(1)

    ' Get the value of the column 1 in the DataTable.
    label1.Text = currentRow(column, _
        DataRowVersion.Current).ToString()
End Sub

Observações

Não version deve ser confundido com a propriedade RowState . O version argumento descreve o estado dos dados contidos pela coluna em relação ao valor original da coluna.

Quando define a propriedade, é gerada uma exceção se esta ocorrer no ColumnChanging evento.

Se esta for uma edição imediata, veja EndEdit as exceções que podem ser geradas.

Ver também

Aplica-se a

Item[Int32, DataRowVersion]

Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs

Obtém os dados armazenados na coluna, especificados pelo índice e versão dos dados a recuperar.

public:
 property System::Object ^ default[int, System::Data::DataRowVersion] { System::Object ^ get(int columnIndex, System::Data::DataRowVersion version); };
public object this[int columnIndex, System.Data.DataRowVersion version] { get; }
member this.Item(int * System.Data.DataRowVersion) : obj
Default Public ReadOnly Property Item(columnIndex As Integer, version As DataRowVersion) As Object

Parâmetros

columnIndex
Int32

O índice zero da coluna.

version
DataRowVersion

Um dos DataRowVersion valores que especifica a versão da linha que queres. Os valores possíveis são Default, Original, Current, e Proposed.

Valor de Propriedade

E Object que contém os dados.

Exceções

O columnIndex argumento está fora de alcance.

Os tipos de dados do valor e da coluna não coincidem.

A linha não tem esta versão dos dados.

Foi feita uma tentativa de definir um valor numa linha eliminada.

Exemplos

O exemplo seguinte obtém o valor atual de uma coluna através da Item[] propriedade do DataRow objeto.

Private Sub DataGrid1_Click _
    (ByVal sender As System.Object, ByVal e As System.EventArgs)
    
    ' Set the current row using the RowNumber property of the CurrentCell.
    Dim currentRow As DataRow = CType(DataGrid1.DataSource, DataTable). _
       Rows(DataGrid1.CurrentCell.RowNumber)

    ' Get the value of the column 1 in the DataTable.
    label1.Text = currentRow(1, DataRowVersion.Current).ToString()
End Sub

Observações

Só pode criar ou atualizar uma linha depois de chamar o BeginEdit método; de forma semelhante, o EndEdit método deve ser chamado para comprometer a edição. Depois de chamar o EndEdit método, e antes de chamar o AcceptChanges método, são armazenadas representações internas dos valores originais e novos propostos. Portanto, até chamar o AcceptChanges, pode usar o version argumento para especificar qual versão do valor de uma coluna precisa, seja o DataRowVersion.Original ou DataRowVersion.Proposed. No entanto, assim que chama o AcceptChanges método, a versão da coluna reverte para DataRowVersion.Original. Se a linha for nova, também pode passar DataRowVersion.Default pelo parâmetro para recuperar o valor padrão da coluna. Ao passar DataRowVersion.Current, a propriedade devolve o valor atual, seja qual for a sua versão.

Note

O BeginEdit método é chamado implicitamente quando se altera o valor de um controlo limitado por dados ou quando um DataRow objeto é adicionado ao DataRowCollection; o EndEdit método é chamado implicitamente quando se chamam os seguintes métodos: o AcceptChanges método do DataRow objeto, o AcceptChanges método do DataTable objeto ou o CancelEdit método.

Em contraste, a DataRowVersion enumeração Current devolve a versão dos dados depois de o EndEdit método ter sido chamado.

O version argumento não deve ser confundido com a RowState propriedade. O version argumento descreve o estado dos dados contidos pela coluna em relação ao valor original da coluna. A RowState propriedade descreve o estado de toda a linha em relação ao seu pai DataTable.

Quando define a propriedade, é gerada uma exceção se esta ocorrer no ColumnChanging evento.

Se esta for uma edição imediata, veja EndEdit as exceções que podem ser geradas.

Aplica-se a

Item[String, DataRowVersion]

Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs
Origem:
DataRow.cs

Obtém a versão especificada dos dados armazenada na coluna nomeada.

public:
 property System::Object ^ default[System::String ^, System::Data::DataRowVersion] { System::Object ^ get(System::String ^ columnName, System::Data::DataRowVersion version); };
public object this[string columnName, System.Data.DataRowVersion version] { get; }
member this.Item(string * System.Data.DataRowVersion) : obj
Default Public ReadOnly Property Item(columnName As String, version As DataRowVersion) As Object

Parâmetros

columnName
String

O nome da coluna.

version
DataRowVersion

Um dos DataRowVersion valores que especifica a versão da linha que queres. Os valores possíveis são Default, Original, Current, e Proposed.

Valor de Propriedade

E Object que contém os dados.

Exceções

A coluna especificada por columnName não pode ser encontrada.

Os tipos de dados do valor e da coluna não coincidem.

A linha não tem esta versão dos dados.

A linha foi apagada.

Exemplos

O exemplo seguinte obtém a versão atual dos dados numa célula clicada de um DataGrid controlo.

private void DataGrid1_Click(object sender, System.EventArgs e)
{
    // Set the current row using the RowNumber
    // property of the CurrentCell.
    DataRow currentRow =
        ((DataTable)(DataGrid1.DataSource)).
        Rows[DataGrid1.CurrentCell.RowNumber];

    // Print the current value of the column named "FirstName."
    Console.WriteLine(currentRow["FirstName",
        DataRowVersion.Current]);
}
Private Sub DataGrid1_Click _
    (ByVal sender As System.Object, ByVal e As System.EventArgs)
    
    ' Set the current row using the RowNumber property 
    ' of the CurrentCell.
    Dim currentRow As DataRow = _
        CType(DataGrid1.DataSource, DataTable). _
        Rows(DataGrid1.CurrentCell.RowNumber)

    ' Print the current value of the column named "FirstName."
    Console.WriteLine(currentRow("FirstName", _
        DataRowVersion.Current).ToString())
End Sub

Observações

A versão não deve ser confundida com a propriedade RowState . O version argumento descreve o estado dos dados contidos pela coluna em relação ao valor original da coluna. A RowState propriedade descreve o estado de toda a linha em relação ao seu pai DataTable.

Quando define a propriedade, é gerada uma exceção se esta ocorrer no ColumnChanging evento.

Se esta for uma edição imediata, veja EndEdit as exceções que podem ser geradas.

Ver também

Aplica-se a