Click here to Skip to main content
15,913,722 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everybody
i have devexpress with agridview i need to export grid content to excel sheet i have used the following code i only have one error in the line
C#
gridView1.GetDataRow(I).Cells[j].Value;

how can i solve it

What I have tried:

C#
int rowsTotal = 0;
int colsTotal = 0;
int I = 0;
int j = 0;
int iC = 0;
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
Excel.Application xlApp = new Excel.Application();

try
{
    Excel.Workbook excelBook = xlApp.Workbooks.Add();
    Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelBook.Worksheets[1];
    xlApp.Visible = true;

    rowsTotal = gridView1.RowCount - 1;
    colsTotal = gridView1.Columns.Count - 1;
    var _with1 = excelWorksheet;
    _with1.Cells.Select();
    _with1.Cells.Delete();
    for (iC = 0; iC <= colsTotal; iC++)
    {
        _with1.Cells[1, iC + 1].Value = gridView1.Columns[iC].Caption;
    }
    for (I = 0; I <= rowsTotal - 1; I++)
    {
        for (j = 0; j <= colsTotal; j++)
        {
            _with1.Cells[I + 2, j + 1].value = gridView1.GetDataRow(I).Cells[j].Value;
            //  _with1.Cells[I + 2, j + 1].value = gridView1.GetRowCellValue(I).ToString();
        }
    }
    _with1.Rows["1:1"].Font.FontStyle = "Bold";
    _with1.Rows["1:1"].Font.Size = 12;

    _with1.Cells.Columns.AutoFit();
    _with1.Cells.Select();
    _with1.Cells.EntireColumn.AutoFit();
    _with1.Cells[1, 1].Select();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
    //RELEASE ALLOACTED RESOURCES
    System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
    xlApp = null;
}
Posted
Updated 12-Oct-16 5:30am

1 solution

WHAT PROBLEM ARE YOU SEEING? After gazing into my crystal ball, I bet you're getting an "index out of range exception".

In my experience, Excel's rows and columns are 1-indexed instead of 0-indexed.
 
Share this answer
 
Comments
MR.alaa 12-Oct-16 15:18pm    
my problem that in gridcontol this part of code works fine gridView1.GetDataRow[I].Cells[j].Value;
but in devexpress i cant reach cell value i get undreline red error under Cells[j].Value;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900