CSD
November 15th, 2005, 06:34 PM
I have a datagrid, and a column called Member. The values in this column's cells are YES or NO. I wish to set the forecolor to green of the value YES when it is YES.
Is this is possible?
Is this is possible?
|
Click to See Complete Forum and Search --> : Change ForeColor based on a value CSD November 15th, 2005, 06:34 PM I have a datagrid, and a column called Member. The values in this column's cells are YES or NO. I wish to set the forecolor to green of the value YES when it is YES. Is this is possible? jhammer November 16th, 2005, 02:22 AM Yes. You will need ColumnStyles. Have a look here: http://j1hammer.blogspot.com/2005/10/how-to-set-forecolor-of-text-in-cell.html CSD November 16th, 2005, 05:07 AM jhammer, I'm currently using ColumnStyles as shown below. Am I able to do what you have sais in the article given the code below? The article has confused me becuase you state that you are deriving from a DataGridTextBoxColumn. // Set the size for the Columns. dgAccountSearchResult.TableStyles[0].GridColumnStyles[0].Width = 0; //AccountID dgAccountSearchResult.TableStyles[0].GridColumnStyles[1].Width = 300; //Tradingname dgAccountSearchResult.TableStyles[0].GridColumnStyles[2].Width = 300; //AccountName dgAccountSearchResult.TableStyles[0].GridColumnStyles[3].Width = 120; //Member jhammer November 16th, 2005, 06:35 AM The article do not discuss the width of the columns, but rather the forecolor of it, based on the value on the cell. In my example I set the forecolor to red if the value is negative. Surely you can figure out how to customize my solution to your needs (Instead of checking the numeric value of the cell, check the string). You must derive from a DataGridColumnStyle in order to accomplish the change of forecolor. Since you are most definitely using DataGridTextBoxColumn (which inherits directly from DataGridColumnStyle), then deriving from that class make sense (unless you are usingyour own custom ColumnStyle, and then you can derive from it). If you need to set the width of the ColumnStyle, then there is no problem since the base class (DataGridTextBoxColumn) support it. Your derived column style will have all the capabilities of the base class, except those you changed in your derived class. I hope this is more clear now. CSD November 16th, 2005, 07:41 AM ok, I have started with placing your first bit of code at the bootom of the form and I get an error of "cannot overide, control.paint is not s function" Keep in mind that I have not placed yor first line of code "PaintedColumnStyle:DataGridTextBoxColumn" anywhere as I don't know where to place it. protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight) { foreBrush = new SolidBrush(GetColor(GetColumnValueAtRow(source,rowNum))); base.Paint (g, bounds, source, rowNum, backBrush, foreBrush, alignToRight); } jhammer November 16th, 2005, 10:15 AM The has been tested, so it runs. Add a new class to the project (PaintedColumnStyle, or whatever you want to call it). place the code in that file. Change the method GetColor to suit your needs. Obviously you had not done so, and that is why you were not able to compile it. You cannot just put parts of the code and expect it to compile. CSD November 16th, 2005, 06:07 PM Ok. I am doing what you have instructed and it's still not working. Below is the new class I have created and its complaining about the DataGridTextBoxColumn in the first line. The error is "are you missing an assembly". Secondly, it also gets an error on CurrencyManager. Obviously you cannot just create a new class and just place the code in it! I'm a beginner with C#.Net but I do understand classes and namespaces etc. Please forgive my ignorance but I would appreciate if you could assist with this as from your posts I get the feeling you are being very short and sweet about this! Please understand with some beginners you have to be a little patient! Having said that now, What am I doing wrong? I have created the class called PaintedColumnStyle and placed the code as stated above with the errors. Thats where I'm at at the moment. public class PaintedColumnStyle:DataGridTextBoxColumn { public PaintedColumnStyle() { // // TODO: Add constructor logic here // } protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight) { foreBrush = new SolidBrush(GetColor(GetColumnValueAtRow(source,rowNum))); base.Paint (g, bounds, source, rowNum, backBrush, foreBrush, alignToRight); } } jhammer November 17th, 2005, 09:49 AM Look, I am only trying to help you, so there is no need to get upset. Since I was asked this question before, I already have the solution, and I posted it in an article on my own free time. As I said before, You cannot just use parts of the code and expect it to work for you. Because you told me you already use column styles I assumed you are familiar with them. Here is the full solution to YOUR problem. I tested it and it work. In your windows application create a class called PaintedColumnStyle (This is almost the same as the code in my article): using System; using System.Drawing; using System.Windows.Forms; namespace YourApplication { public class PaintedColumnStyle:DataGridTextBoxColumn { protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight) { foreBrush = new SolidBrush(GetColor(GetColumnValueAtRow(source,rowNum))); base.Paint (g, bounds, source, rowNum, backBrush, foreBrush, alignToRight); } private Color GetColor(object text) { if (text == DBNull.Value) return Color.Black; string str; try { if (text.GetType() == typeof(string) ) str = (string) text; else str = text.ToString(); } catch { return Color.Black; } if (str=="Yes") return Color.Green; return Color.Black; } } } Drag a DataGrid to the form, and double click on the form to create a Form_Load event: private void Form1_Load(object sender, System.EventArgs e) { //Creating a test DataTable. Replace this with your datatable. DataTable dt = new DataTable("SomeTable"); dt.Columns.Add(new DataColumn("SomeColumn")); dt.Columns.Add(new DataColumn("YesNo")); //This is your column DataRow dr = dt.NewRow(); dr["SomeColumn"] = "a"; dr["YesNo"] = "Yes"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["SomeColumn"] = "b"; dr["YesNo"] = "No"; dt.Rows.Add(dr); dataGrid1.DataSource = dt; //Customising the grid //Initialize objects DataGridTableStyle ts = new DataGridTableStyle(); DataGridTextBoxColumn cs1 = new DataGridTextBoxColumn(); PaintedColumnStyle cs2 = new PaintedColumnStyle(); //Setting a DataView as the DataSource dataGrid1.BeginInit(); DataView dv = new DataView(dt); dataGrid1.DataSource = dv; // ts dataGrid1.TableStyles.AddRange(new DataGridTableStyle[] {ts}); ts.DataGrid = dataGrid1; ts.GridColumnStyles.AddRange(new DataGridColumnStyle[] {cs1,cs2}); ts.MappingName = "SomeTable"; // This is the name of the table you are binding to. // cs1 cs1.HeaderText = "SomeColumn"; // This is the text that is written in the Column Header. Leave empty to show the name of the column. cs1.MappingName = "SomeColumn"; // This is the name of the column.amountColumn.ReadOnly = false; cs1.Width = 100; // cs2 cs2.HeaderText = "Yes/No"; cs2.MappingName = "YesNo"; // This is the name of the column. cs2.ReadOnly = true; cs2.Width = 75; dataGrid1.EndInit(); } Run the application and see for yourself that the DataGrid is filled with a table with two rows, and the Yes cell is painted in green. CSD November 17th, 2005, 07:38 PM jhammer. Thanks for that. I have it working. Just 1 thing though, how do you clear the datagrid result? The reason is when you do another serch and fill in the datagrid the initial data is still there. so what ends up happening is miltiple columns are getting created in the datagrid. Is there a way to clear the mapping names? I did try the code below at the very top of my procedure, but it doesn't do the trick. datagrid1.TableStyles.Clear(); jhammer November 18th, 2005, 08:21 AM You can remove the TableStyle and add another one. I don't understand how more column styles are created. Unless you add them manually, they can't be created. Please tell me exactly what you are doing. CSD November 21st, 2005, 01:00 AM Ok. What I have is a form that has a datagrid. This form has search options such as AccountName, TradingName, ContactSurName etc... All of the searches use the datagrid to display the corresponding result set. Now, having said that I have have to create several tablestyles to suit each individual result set. 1 table style for the AccountName search, 1 for the TradingName and 1 for the ContactSurName because they all have different columns returning in a DataSet. Now that you have given me the example on how to change the forecolor based on a value, I have the following code below for the AccountName Search. I have now emulated the code below for each of the types of searches. You search for an AccountName and it works. It will display AccountName and the Member Column with the Member Column displaying Green color for the word "Yes". The problem is that when you do another search on another AccountName, the Columns get appended to the datagrid instead of overrighting the current data that is in the datagrid. In other words, onthe second search, you will see AccountName, Member, AccountName, Member. This will keep going for as many searches you do. This is happening on the TradingName & ContactSurName search as well. DataSet DSSearchAccount = new DataSet(); try { DSSearchAccount = DataAccess.SearchAccount(AccountName); this.dgAccountSearchResult.DataSource = DSSearchAccount.Tables[0]; DataGridTextBoxColumn cs1 = new DataGridTextBoxColumn(); DataGridTextBoxColumn cs2 = new DataGridTextBoxColumn(); PaintedColumnStyle cs3 = new PaintedColumnStyle(); // ts dgAccountSearchResult.TableStyles.AddRange(new DataGridTableStyle[] {acc}); acc.DataGrid = dgAccountSearchResult; acc.GridColumnStyles.AddRange(new DataGridColumnStyle[] {cs1, cs2, cs3}); acc.MappingName = "Account"; // This is the name of the table you are binding to. MessageBox.Show("Here!"); // cs1 cs1.HeaderText = "AccountID"; // This is the text that is written in the Column Header. Leave empty to show the name of the column. cs1.MappingName = "AccountID"; // This is the name of the column.amountColumn.ReadOnly = false; cs1.Width = 0; // cs2 cs2.HeaderText = "Account Name"; // This is the text that is written in the Column Header. Leave empty to show the name of the column. cs2.MappingName = "Account Name"; cs2.Width = 300; // cs3 cs3.HeaderText = "Member"; cs3.MappingName = "Member"; // This is the name of the column. cs3.Width = 100; //Set the Header Font to Bold. dgAccountSearchResult.TableStyles[0].HeaderFont = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } jhammer November 21st, 2005, 02:52 AM What I suggest is this: - Create a TableStyle for each view you want (with all the columns and MAppingNames), and store them in a HashTable (for example map TableNames to TableStyles). Do that in advance. - Whenever you want to switch views, remove the current TableStyle from the grid TableStyles collection, and add the appropriate TableStyle from the HashTable. CSD November 21st, 2005, 05:40 AM Ok I will give that a go but keep in mind that I'm not using a dataview but rather a dataset. Does this make a difference? In the mean time I will try what you have suggested. jhammer November 21st, 2005, 07:26 AM If you are binding to a DataSet then what I have suggested might not work. I will need to check for myself. Why are you binding to a DataSet? Do you need to see the relations in the same GUI? Or is this just a matter of convenience? CSD November 21st, 2005, 06:32 PM Its purely a matter of convenience. CSD November 21st, 2005, 06:41 PM jhammer, I tried what you said, that is to remove the tablestyle when you switch the search but for some reason the application terminates with an error of "This DataGridTable does not exist in the collection." The line of code is; dgAccountSearchResult.TableStyles.Remove(acc); And it displays a green line in the main function of the Application. The main function has some code in there that prevents users from starting the Application more than once. Below is the code for that and the green line is on the "GC.KeepAlive(m);" bool createdNew; Mutex m = new Mutex(true, "BMCorpInfo", out createdNew); if (! createdNew) { // App is already running... MessageBox.Show("Only one instance of this application is allowed at a time.", "BMCORPInfo", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Application.EnableVisualStyles(); Application.Run(new MainMenu()); // keep the mutex reference alive until the normal termination of the program GC.KeepAlive(m); codeguru.com
Copyright Internet.com Inc., All Rights Reserved. |