Solved

Need Help Gridview C# ASP.Net

Posted on 2008-10-16
24
750 Views
Last Modified: 2013-12-17
Hi,

I have a gridview that displays dynimic saved views. So the user will pick a name from the lst which will include the whole sql query to change gridview.

I have attached my code snippet. What I am trying to achieve here, is when selected fields that are selected or in the query would like to display them with a set background colour (as each colour represents a group). Normally this can easily be achieved via HTML side but as it is dynmic and data can be changed at any time, I have no idea how I can do this!

So going by my code, the gridview is inistially hidden, then when a selection is made in the view list box sets the gridview to true and then displays it in the browser.

Now the selected view can be any fields, as these are created and used. So I need to have something that can determine what is the output and set the right background colour to the fields that are chosen that I have pre-defined.

I dont think there is no other way of explaining what I need to do. Any more information regarding what I am trying to do, please let me know.

Regards,

introlux

======================================================================
 

HTML
 

======================================================================
 

        <asp:GridView ID="GridView1" runat="server" CellPadding="3" DataSourceID="AccessDataSource1"

            ForeColor="Black" GridLines="Vertical" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px">

            <FooterStyle BackColor="#CCCCCC" />

            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />

            <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />

            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />

            <AlternatingRowStyle BackColor="#CCCCCC" />

        </asp:GridView>

        <br />

        <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/db1.mdb"

            SelectCommand="SELECT Name AS Name1, Age AS Age1, Gender AS Gender1 FROM [tblProCom]">

        </asp:AccessDataSource>
 

==================================================================
 

Code behind
 

==================================================================
 

    protected void Page_Load(object sender, EventArgs e)

    {

        Page.MaintainScrollPositionOnPostBack = true;

    }
 
 

    protected void lstView_SelectedIndexChanged(object sender, EventArgs e)

    {

        check();

    }
 

    void check()

    {

        this.GridView1.Visible = true;

        string SQL;

        SQL = "SELECT " + lstView.SelectedValue;

        OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("App_Data/db1.mdb"));

        OleDbCommand objCmd = new OleDbCommand(SQL, objConn);
 

        this.AccessDataSource1.Dispose(); //delete

        this.AccessDataSource1.SelectCommand = SQL; //use new select query

        this.AccessDataSource1.DataBind(); //create new

    }

Open in new window

0
Comment
Question by:introlux
  • 13
  • 6
  • 5
24 Comments
 
LVL 8

Expert Comment

by:unmeshdave
Comment Utility
I guess you want to display columns in different back ground colors.


To do that, first of all you can get the datasource what you are binding with girdview.

Say your Gridview is Gridview1. After binding, you can use following.
DataSet ds = GridView1.DataSource as DataSet;

this way you can get dataset which is currently bound to Gridview. and you can go through each column of gridview.

to set the background color of a column in gridview you can use
GridView1.Columns[index].ItemStyle.BackColor
0
 
LVL 3

Expert Comment

by:JunkMan
Comment Utility
If I understood you correctly you would know what colors to set for wich fields, for example that age would be green, name would be blue and so forth?

If that is the case you can make use of the RowDataBound event of the gridview. Like attached,

Obviously this all depends if i understood the question correctly and you are able to show the header.
    Dictionary<int, string> columnColors = new Dictionary<int, string>();

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        for (int i = 0; i < e.Row.Cells.Count; i++)

        {

            TableCell cell = e.Row.Cells[i];

            if (e.Row.RowType == DataControlRowType.Header)

            {

                //figure out the colors to set for each column

                if (cell.Text.Equals("age", StringComparison.CurrentCultureIgnoreCase))

                    columnColors.Add(i, "green");

                else if (cell.Text.Equals("name", StringComparison.CurrentCultureIgnoreCase))

                    columnColors.Add(i, "blue");
 

            }

            else if (e.Row.RowType == DataControlRowType.DataRow)

            {

                if (columnColors.ContainsKey(i))

                    cell.Style.Add("color", columnColors[i]);

            }

        }

    }

Open in new window

0
 

Author Comment

by:introlux
Comment Utility
Compiler Error Message: CS0246: The type or namespace name 'Dictionary' could not be found (are you missing a using directive or an assembly reference?)

Source Error:

 

Line 229:    }
Line 230:
Line 231:    Dictionary<int, string> columnColors = new Dictionary<int, string>();
Line 232:    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
Line 233:    {
 
0
 
LVL 3

Expert Comment

by:JunkMan
Comment Utility
what version of .net are you using?

make sure you are using System.Collections.Generic on the top of your page.
0
 
LVL 3

Expert Comment

by:JunkMan
Comment Utility
sorry should have been clearer if you are using Framework 2.0 or above, just add the following to the top of your page:
using System.Collections.Generic;

Open in new window

0
 

Author Comment

by:introlux
Comment Utility
ASP.Net 2.0

Where is this code placed:

 Dictionary<int, string> columnColors = new Dictionary<int, string>();
0
 

Author Comment

by:introlux
Comment Utility
I think the problem lies on this code:

Dictionary<int, string> columnColors = new Dictionary<int, string>();

As the code cannot refer to columnColors and causes an error
0
 

Author Comment

by:introlux
Comment Utility
Compiler Error Message: CS1501: No overload for method 'check' takes '0' arguments

Source Error:

 

Line 290:    protected void lstView_SelectedIndexChanged(object sender, EventArgs e)
Line 291:    {
Line 292:        check();
Line 293:        btnExport.Visible = true;
 

    Dictionary<int, string> columnColors = new Dictionary<int, string>();
 

    protected void check(object sender, GridViewRowEventArgs e)

    {

        this.GridView1.Visible = true;

        string SQL;

        SQL = "SELECT " + lstView.SelectedValue;

        OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("App_Data/ProCom.mdb"));

        OleDbCommand objCmd = new OleDbCommand(SQL, objConn);
 

        this.AccessDataSource1.Dispose(); //delete

        this.AccessDataSource1.SelectCommand = SQL; //use new select query

        this.AccessDataSource1.DataBind(); //create new

       

        for (int i = 0; i < e.Row.Cells.Count; i++)

        {

            TableCell cell = e.Row.Cells[i];

            if (e.Row.RowType == DataControlRowType.Header)

            {

                //figure out the colors to set for each column

                if (cell.Text.Equals("Pid", StringComparison.CurrentCultureIgnoreCase))

                    columnColors.Add(i, "green");

                else if (cell.Text.Equals("PName", StringComparison.CurrentCultureIgnoreCase))

                    columnColors.Add(i, "blue");
 

            }

            else if (e.Row.RowType == DataControlRowType.DataRow)

            {

                if (columnColors.ContainsKey(i))

                    cell.Style.Add("color", columnColors[i]);

            }

        }

    }

Open in new window

0
 
LVL 3

Expert Comment

by:JunkMan
Comment Utility
I'm sorry but you've completely missed the point!.. The code i've provided is not meant to replace your existing check method. It is meant to handle your gridview's rowdatabound event.

Notice the OnRowDataBound="GridView1_RowDataBound" on the attached code.
 <asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" runat="server" CellPadding="3" DataSourceID="AccessDataSource1"

            ForeColor="Black" GridLines="Vertical" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px">

            <FooterStyle BackColor="#CCCCCC" />

            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />

            <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />

            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />

            <AlternatingRowStyle BackColor="#CCCCCC" />

        </asp:GridView>

Open in new window

0
 

Author Comment

by:introlux
Comment Utility
Compiler Error Message: CS1501: No overload for method 'check' takes '0' arguments

Source Error:

 

Line 268:    protected void lstView_SelectedIndexChanged(object sender, EventArgs e)
Line 269:    {
Line 270:        check();
Line 271:    }
 

=======================================================================
 

FRONT CODE
 

=======================================================================
 

        <asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" runat="server" CellPadding="3" DataSourceID="AccessDataSource1"

            ForeColor="Black" GridLines="Vertical" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px">

            <FooterStyle BackColor="#CCCCCC" />

            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />

            <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />

            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />

            <AlternatingRowStyle BackColor="#CCCCCC" />

        </asp:GridView>
 

=======================================================================
 

CODE BEHIND
 

=======================================================================
 

    protected void check(object sender, GridViewRowEventArgs e)

    {

        this.GridView1.Visible = true;

        string SQL;

        SQL = "SELECT " + lstView.SelectedValue;

        OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("App_Data/ProCom.mdb"));

        OleDbCommand objCmd = new OleDbCommand(SQL, objConn);
 

        this.AccessDataSource1.Dispose(); //delete

        this.AccessDataSource1.SelectCommand = SQL; //use new select query

        this.AccessDataSource1.DataBind(); //create new

    }
 

    Dictionary<int, string> columnColors = new Dictionary<int, string>();
 

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        for (int i = 0; i < e.Row.Cells.Count; i++)

        {

            TableCell cell = e.Row.Cells[i];

            if (e.Row.RowType == DataControlRowType.Header)

            {

                //figure out the colors to set for each column

                if (cell.Text.Equals("Pid", StringComparison.CurrentCultureIgnoreCase))

                    columnColors.Add(i, "green");

                else if (cell.Text.Equals("PName", StringComparison.CurrentCultureIgnoreCase))

                    columnColors.Add(i, "blue");
 

            }

            else if (e.Row.RowType == DataControlRowType.DataRow)

            {

                if (columnColors.ContainsKey(i))

                    cell.Style.Add("color", columnColors[i]);

            }

        }

    }
 

    protected void lstView_SelectedIndexChanged(object sender, EventArgs e)

    {

        check();

    }

Open in new window

0
 
LVL 3

Expert Comment

by:JunkMan
Comment Utility
compiler is correct, your check method is expecting argument!... please remove object sender, GridViewRowEventArgs e

from

protected void check(object sender, GridViewRowEventArgs e)
0
 

Author Comment

by:introlux
Comment Utility
When doing this, i get the following error:

Compiler Error Message: CS0103: The name 'e' does not exist in the current context

Source Error:

 

Line 234:    protected void GridView1_RowDataBound()
Line 235:    {
Line 236:        for (int i = 0; i < e.Row.Cells.Count; i++)
Line 237:        {
Line 238:            TableCell cell = e.Row.Cells[i];
 
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 3

Assisted Solution

by:JunkMan
JunkMan earned 200 total points
Comment Utility
try this:
    protected void check()

    {

        this.GridView1.Visible = true;

        string SQL;

        SQL = "SELECT " + lstView.SelectedValue;

        OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("App_Data/ProCom.mdb"));

        OleDbCommand objCmd = new OleDbCommand(SQL, objConn);

 

        this.AccessDataSource1.Dispose(); //delete

        this.AccessDataSource1.SelectCommand = SQL; //use new select query

        this.AccessDataSource1.DataBind(); //create new

    }

 

    Dictionary<int, string> columnColors = new Dictionary<int, string>();

 

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        for (int i = 0; i < e.Row.Cells.Count; i++)

        {

            TableCell cell = e.Row.Cells[i];

            if (e.Row.RowType == DataControlRowType.Header)

            {

                //figure out the colors to set for each column

                if (cell.Text.Equals("Pid", StringComparison.CurrentCultureIgnoreCase))

                    columnColors.Add(i, "green");

                else if (cell.Text.Equals("PName", StringComparison.CurrentCultureIgnoreCase))

                    columnColors.Add(i, "blue");

 

            }

            else if (e.Row.RowType == DataControlRowType.DataRow)

            {

                if (columnColors.ContainsKey(i))

                    cell.Style.Add("color", columnColors[i]);

            }

        }

    }

 

    protected void lstView_SelectedIndexChanged(object sender, EventArgs e)

    {

        check();

    }

Open in new window

0
 

Author Comment

by:introlux
Comment Utility
I have done this - All compiles but no change of colour...........
0
 

Author Comment

by:introlux
Comment Utility
Yes - Got it to work, but what is does it changes the text rather than the heading. The whole colour text (only data) is displayed with the relevant colour
0
 
LVL 8

Expert Comment

by:unmeshdave
Comment Utility
so do u want to change one complete column with one color or only heading of that column?
 and do u want to change text color or background color?

If you want to give different colors to different columns(complete column), I have already given solution in very first place. Its easy and performance wise preferred.
0
 

Author Comment

by:introlux
Comment Utility
ONLY headings

The colour text etc... can stay the same. I just want the Forcolour of the background of the headings changed, depended on what they choose.

I do not need to change the text colour.

Regards,

introlux
0
 
LVL 8

Expert Comment

by:unmeshdave
Comment Utility
I changed the code little bit. It is only one function which is changed other code remains same. you can try that. It changes the back ground of headers only.
If you do not want to change the background color of heading and want to change only text color of headings

just replace this line in the code attached
cell.BackColor = columnColors[i]; //this is for background color

with this one
cell.ForeColor = columnColors[i]; //this is for Forecolor color
 

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        for (int i = 0; i < e.Row.Cells.Count; i++)

        {

            TableCell cell = e.Row.Cells[i];

            if (e.Row.RowType == DataControlRowType.Header)

            {

                //figure out the colors to set for each column

                if (cell.Text.Equals("Pid", StringComparison.CurrentCultureIgnoreCase))

                    columnColors.Add(i, "green");

                else if (cell.Text.Equals("PName", StringComparison.CurrentCultureIgnoreCase))

                    columnColors.Add(i, "blue");
 

                //the added line

                cell.BackColor = columnColors[i];

 

            }

            //FOLLOWING LINES REMOVED

            //else if (e.Row.RowType == DataControlRowType.DataRow)

            //{

            //    if (columnColors.ContainsKey(i))

            //        cell.Style.Add("color", columnColors[i]);

            //}

        }

    }

Open in new window

0
 

Author Comment

by:introlux
Comment Utility
Line 247:
Line 248:                //the added line
Line 249:                cell.BackColor = columnColors[i];
Line 250:
Line 251:            }
0
 

Author Comment

by:introlux
Comment Utility
Compiler Error Message: CS0029: Cannot implicitly convert type 'string' to 'System.Drawing.Color'

Source Error:
0
 
LVL 8

Accepted Solution

by:
unmeshdave earned 300 total points
Comment Utility
Sorry Actually I tried to keep ur existing code. I chaned the code again.

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        for (int i = 0; i < e.Row.Cells.Count; i++)

        {

            TableCell cell = e.Row.Cells[i];

            if (e.Row.RowType == DataControlRowType.Header)

            {

                //figure out the colors to set for each column

                if (cell.Text.Equals("Pid", StringComparison.CurrentCultureIgnoreCase))

                    cell.BackColor = System.Drawing.Color.Green;

                else if (cell.Text.Equals("PName", StringComparison.CurrentCultureIgnoreCase))

                    cell.BackColor =  System.Drawing.Color.Blue; 

            }

        }

    }

Open in new window

0
 

Author Closing Comment

by:introlux
Comment Utility
AT LAST!!!! Thank you so much for your support guys!
0
 

Author Comment

by:introlux
Comment Utility
One last thing - Instead of using a predefined colour can i used a colour for example: #99ffcc

If so, how will i implement this?

Regards,

introlux
0
 
LVL 8

Expert Comment

by:unmeshdave
Comment Utility
u can use FromName method of System.drawing.color class.

http://msdn.microsoft.com/en-us/library/system.drawing.color.fromname.aspx
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
I see at least one EE question a week that pertains to using temporary tables in MS Access.  But surprisingly, I was unable to find a single article devoted solely to this topic. I don’t intend to describe all of the uses of temporary tables in t…
Familiarize people with the process of utilizing SQL Server stored procedures from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Micr…
With Microsoft Access, learn how to start a database in different ways and produce different start-up actions allowing you to use a single database to perform multiple tasks. Specify a start-up form through options: Specify an Autoexec macro: Us…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now