Cory
Cory

Reputation: 161

Formatting Cells on Gridview from SQL Data Reader

I have a Grid view which populates through my SQL data reader

Grid View:

<asp:GridView ID="gridviewALL" runat="server" OnItemDataBound="Search_ItemDataBound">
</asp:GridView>

SQL Data Reader:

SqlCommand cmd = new SqlCommand("SELECT en.dpCreatedDT AS 'Time Received', en.enStatusCH AS 'Status', en.enNotificationNoNI AS 'LSBUD Ref', cm.cmpersonfirstch AS 'First Name', cm.cmPersonLastCH AS 'Last Name', cm.cmcompanynamech AS 'Company' FROM dp_enquiry en JOIN dp_caller_master cm ON (en.encmcallerkeyfk = cm.cmCallerKeyNI) WHERE en.ennotificationnoni = @JobnoALL", conn);
        try
        {
            SqlParameter search = new SqlParameter();
            search.ParameterName = "@JobnoALL";
            search.Value = JobnoALL.Text.Trim();
            cmd.Parameters.Add(search);
            SqlDataReader dr = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(dr);
            gridviewALL.DataSource = dt;
            gridviewALL.DataBind();
        }

I'm trying to change the format of a cell in the grid view when the text equals a value, I've done this using a listview before but the Gridview steps seems different. I have the following which doesn't seem to be working any suggestions?

private void Search_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
    string CurrentColumn = e.Item.Cells[1].Text;
    if (CurrentColumn == "PROC")
    {
        e.Item.Cells[1].Text = "Creating PDF";
    }
    else if (CurrentColumn == "CLOS")
    {
        e.Item.Cells[1].Text = "Complete";
        e.Item.Cells[1].ForeColor = System.Drawing.Color.Green;
    }
}

Upvotes: 0

Views: 472

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 21805

It must be reading the header, you need to check if its a DataRow:-

 if (e.Row.RowType == DataControlRowType.DataRow)
 {
    string CurrentColumn = e.Item.Cells[1].Text;
    //your code goes here..
 }

Also, I would suggest you to use DataBinder.Eval method instead to avoid hard-coding of cell index as it may result in error if order of columns change.

string CurrentColumn = DataBinder.Eval(e.Row.DataItem, "yourColumnName").ToString();

Update:

Just noticied you are using ItemDataBound which is an event for DataGrid and not Gridview. Use RowDataBound event instead:-

<asp:GridView ID="gridviewALL" runat="server" OnRowDataBound="gridviewALL_RowDataBound">
</asp:GridView>

Your rowDataBound event should look like this:-

protected void gridviewALL_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //your code here
}

Upvotes: 3

Related Questions