开发者

Convert empty cells in a data table to 0

I have a data table that has 1 column having few cells having null value. How can I convert them to 0 ?

I bind this data table to a data grid view and cells are empty in case of null in the data tab开发者_运维问答le.I need to have 0 displayed in the datagridview.


Edit your cell template and set the NullValue to 0


Honestly, I'd clear this up before binding to the datagrid. I'd execute a for loop and just change all the DBNull values to 0. Its quick, easy, understandable code. This has the benefit of actually changing the data to 0, instead of changing how it is viewed to 0, as others have suggested by making tweaks to the dataGrid. Either strategy has merits, just depends on what you want to do.

Try this:

for (int i = 0; i < dataTable.Rows.Count; i++)
{
    DataRow row = dataTable.Rows[i];

    if (row["ColumnA"] == DBNull.Value)
    {
        row["ColumnA"] = 0;
    }
}


I set the property of the DataGridViewTextBox column .Seems to be working as expected.

amountColumn.DefaultCellStyle.NullValue = "0"; 


If you fetch data to display from database then you might bind null to 0 using following syntax:

SELECT ISNULL(ColumnName, 0)
FROM TableName;


this works for all rows and columns with null or empty values

For i As Integer = 0 To output.Tables(0).Rows.Count - 1
        Dim row As DataRow = output.Tables(0).Rows(i)

        For j As Integer = 0 To output.Tables(0).Columns.Count - 1
            If row(j) Is DBNull.Value Then
                row(j) = 0
            End If
            If row(j).ToString.Length = 0 Then
                row(j) = 0
            End If
        Next

    Next

C#

for (int i = 0; i <= output.Tables[0].Rows.Count - 1; i++)
{
    DataRow row = output.Tables[0].Rows[i];
    for (int j = 0; j <= output.Tables[0].Columns.Count - 1; j++)
    {
        if (object.ReferenceEquals(row[j], DBNull.Value))
        {
            row[j] = 0;
        }
        if (row[j].ToString().Length == 0)
        {
            row[j] = 0;
        }
    }
}


Try this:

 for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            for (int j = 0; j < dt.Columns.Count; j++)
                            {
                                if (string.IsNullOrEmpty(dt.Rows[i][j].ToString()))
                                {

                                    dt.Rows[i][j] = "0";
                                }
                            }
                        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜