Two different formats in the datagridview column

huangapple go评论59阅读模式
英文:

Two different formats in the datagridview column

问题

I have a column called Discount Value in DataGridView which has two different formats namely Currency and Percentage.

Is it possible to do a different format on one column of the DataGridView? Thanks.

I tried using the code below but the output is not as expected. Problem in RegulerDiscount_DataGridView_CellFormatting

	namespace WinFormsApp1
	{
		public partial class Form1 : Form
		{
			public Form1()
			{
				InitializeComponent();

				List<RegulerDiscountModel> regulerDiscountModelList = new List<RegulerDiscountModel>();

				RegulerDiscountModel regulerDiscountModel1 = new RegulerDiscountModel();
				regulerDiscountModel1.RegulerDiscountID = 1;
				regulerDiscountModel1.RegulerDiscountProductId = 1;
				regulerDiscountModel1.RegulerDiscountProductName = "Product 1";
				regulerDiscountModel1.RegulerDiscountName = "Disc1";
				regulerDiscountModel1.RegulerDiscountValue = 1000;
				regulerDiscountModel1.RegulerDiscountStrTypeId = "Rp";
				regulerDiscountModelList.Add(regulerDiscountModel1);

				RegulerDiscountModel regulerDiscountModel2 = new RegulerDiscountModel();
				regulerDiscountModel2.RegulerDiscountID = 1;
				regulerDiscountModel2.RegulerDiscountProductId = 1;
				regulerDiscountModel2.RegulerDiscountProductName = "Product 1";
				regulerDiscountModel2.RegulerDiscountName = "Disc2";
				regulerDiscountModel2.RegulerDiscountValue = 2000;
				regulerDiscountModel2.RegulerDiscountStrTypeId = "Rp";
				regulerDiscountModelList.Add(regulerDiscountModel2);

				RegulerDiscountModel regulerDiscountModel3 = new RegulerDiscountModel();
				regulerDiscountModel3.RegulerDiscountID = 1;
				regulerDiscountModel3.RegulerDiscountProductId = 1;
				regulerDiscountModel3.RegulerDiscountProductName = "Product 1";
				regulerDiscountModel3.RegulerDiscountName = "Disc3";
				regulerDiscountModel3.RegulerDiscountValue = 10.5;
				regulerDiscountModel3.RegulerDiscountStrTypeId = "%";
				regulerDiscountModelList.Add(regulerDiscountModel3);

				RegulerDiscountModel regulerDiscountModel4 = new RegulerDiscountModel();
				regulerDiscountModel4.RegulerDiscountID = 1;
				regulerDiscountModel4.RegulerDiscountProductId = 1;
				regulerDiscountModel4.RegulerDiscountProductName = "Product 1";
				regulerDiscountModel4.RegulerDiscountName = "Disc4";
				regulerDiscountModel4.RegulerDiscountValue = 20.1;
				regulerDiscountModel4.RegulerDiscountStrTypeId = "%";
				regulerDiscountModelList.Add(regulerDiscountModel4);

				CtechGroupedDataGridView.DataSource = regulerDiscountModelList;
				CtechGroupedDataGridView.CellFormatting += CtechGroupedDataGridView_CellFormatting;
			}

			private void CtechGroupedDataGridView_CellFormatting(object? sender, DataGridViewCellFormattingEventArgs e)
			{
				try
				{
					if (e.RowIndex >= 0 && e.RowIndex <= CtechGroupedDataGridView.Rows.Count - 1)
					{
						DataGridViewRow row = CtechGroupedDataGridView.CurrentRow;
						if (row != null)
						{
							// ID ProductId ProductName DiscountName DiscountValue DiscountType
							// 0  1         2           3            4             5

							if (row.Cells[4].Value != null && row.Cells[5].Value != null)
							{
								String? strDiscountValue = row.Cells[4].Value.ToString();
								String? strDiscountType = row.Cells[5].Value.ToString();
								if (!String.IsNullOrEmpty(strDiscountValue) && !String.IsNullOrEmpty(strDiscountType))
								{
									switch (strDiscountType)
									{
										case "Rp":
											CtechGroupedDataGridView[4, e.RowIndex].Style.Format = "N0";
											break;

										case "%":
											CtechGroupedDataGridView[4, e.RowIndex].Style.Format = "P1";
											break;
									}
								}
							}
						}
					}
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}
	}

Current Output:
Two different formats in the datagridview column

When I clicked on DataGridView, I get Output as follows:
[![enter image description here][2]][2]

Expected output:
Two different formats in the datagridview column

Grouped DataGridView (it's works)

	namespace WinFormsApp1
	{
		public partial class CtechGroupedDataGridView : DataGridView
		{
			public CtechGroupedDataGridView()
			{
				InitializeComponent();

				DoubleBuffered = true;
				GridColor = Color.LightGray;
				BackgroundColor = SystemColors.Control;
				BorderStyle = BorderStyle.None;
				SelectionMode = DataGridViewSelectionMode.FullRowSelect;
				ColumnGroupEnabled = new int[] { 1, 2};

				ClearSelection();
			}

			protected override void OnDataBindingComplete(DataGridViewBindingCompleteEventArgs e)
			{
				base.OnDataBindingComplete(e);

				// Fit columns
				int columnsWidth = 0;
				foreach (DataGridViewColumn column in this.Columns)
				{
					if (column.Visible)
					{
						columnsWidth += column.Width;
					}
				}

				if (columnsWidth < this.Width)
				{
					for (int i = 0; i < this.Columns.Count; i++)
					{
						this.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
					}
					this.Columns[this.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
				}
				else
				{
					for (int i = 0; i < this.Columns.Count; i++)
					{
						this.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
					}
				}

				for (int i = 0; i < this.Columns.Count; i++)
				{
					int column = this.Columns[i].Width;
					this.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
					this.Columns[i].Width = column;
					this.Columns[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
				}

				ClearSelection();
			}


			protected override void OnCellFormatting(DataGridViewCellFormattingEventArgs args)
			{
				// Call home to base
				base.On

<details>
<summary>英文:</summary>

I have a **column** called **Discount Value** in **DataGridView** which has **two different formats** namely **Currency** and **Percentage**. 

Is it possible to do a **different format** on one **column** of the **DataGridView**? Thanks.

I tried using the code below but the output is not as expected. Problem in **RegulerDiscount_DataGridView_CellFormatting** 

	namespace WinFormsApp1
	{
		public partial class Form1 : Form
		{
			public Form1()
			{
				InitializeComponent();

				List&lt;RegulerDiscountModel&gt; regulerDiscountModelList = new List&lt;RegulerDiscountModel&gt;();

				RegulerDiscountModel regulerDiscountModel1 = new RegulerDiscountModel();
				regulerDiscountModel1.RegulerDiscountID = 1;
				regulerDiscountModel1.RegulerDiscountProductId = 1;
				regulerDiscountModel1.RegulerDiscountProductName = &quot;Product 1&quot;;
				regulerDiscountModel1.RegulerDiscountName = &quot;Disc1&quot;;
				regulerDiscountModel1.RegulerDiscountValue = 1000;
				regulerDiscountModel1.RegulerDiscountStrTypeId = &quot;Rp&quot;;
				regulerDiscountModelList.Add(regulerDiscountModel1);

				RegulerDiscountModel regulerDiscountModel2 = new RegulerDiscountModel();
				regulerDiscountModel2.RegulerDiscountID = 1;
				regulerDiscountModel2.RegulerDiscountProductId = 1;
				regulerDiscountModel2.RegulerDiscountProductName = &quot;Product 1&quot;;
				regulerDiscountModel2.RegulerDiscountName = &quot;Disc2&quot;;
				regulerDiscountModel2.RegulerDiscountValue = 2000;
				regulerDiscountModel2.RegulerDiscountStrTypeId = &quot;Rp&quot;;
				regulerDiscountModelList.Add(regulerDiscountModel2);

				RegulerDiscountModel regulerDiscountModel3 = new RegulerDiscountModel();
				regulerDiscountModel3.RegulerDiscountID = 1;
				regulerDiscountModel3.RegulerDiscountProductId = 1;
				regulerDiscountModel3.RegulerDiscountProductName = &quot;Product 1&quot;;
				regulerDiscountModel3.RegulerDiscountName = &quot;Disc3&quot;;
				regulerDiscountModel3.RegulerDiscountValue = 10.5;
				regulerDiscountModel3.RegulerDiscountStrTypeId = &quot;%&quot;;
				regulerDiscountModelList.Add(regulerDiscountModel3);

				RegulerDiscountModel regulerDiscountModel4 = new RegulerDiscountModel();
				regulerDiscountModel4.RegulerDiscountID = 1;
				regulerDiscountModel4.RegulerDiscountProductId = 1;
				regulerDiscountModel4.RegulerDiscountProductName = &quot;Product 1&quot;;
				regulerDiscountModel4.RegulerDiscountName = &quot;Disc4&quot;;
				regulerDiscountModel4.RegulerDiscountValue = 20.1;
				regulerDiscountModel4.RegulerDiscountStrTypeId = &quot;%&quot;;
				regulerDiscountModelList.Add(regulerDiscountModel4);

				CtechGroupedDataGridView.DataSource = regulerDiscountModelList;
				CtechGroupedDataGridView.CellFormatting += CtechGroupedDataGridView_CellFormatting;
			}

			private void CtechGroupedDataGridView_CellFormatting(object? sender, DataGridViewCellFormattingEventArgs e)
			{
				try
				{
					if (e.RowIndex &gt;= 0 &amp;&amp; e.RowIndex &lt;= CtechGroupedDataGridView.Rows.Count - 1)
					{
						DataGridViewRow row = CtechGroupedDataGridView.CurrentRow;
						if (row != null)
						{
							// ID ProductId ProductName DiscountName DiscountValue DiscountType
							// 0  1         2           3            4             5

							if (row.Cells[4].Value != null &amp;&amp; row.Cells[5].Value != null)
							{
								String? strDiscountValue = row.Cells[4].Value.ToString();
								String? strDiscountType = row.Cells[5].Value.ToString();
								if (!String.IsNullOrEmpty(strDiscountValue) &amp;&amp; !String.IsNullOrEmpty(strDiscountType))
								{
									switch (strDiscountType)
									{
										case &quot;Rp&quot;:
											CtechGroupedDataGridView[4, e.RowIndex].Style.Format = &quot;N0&quot;;
											break;

										case &quot;%&quot;:
											CtechGroupedDataGridView[4, e.RowIndex].Style.Format = &quot;P1&quot;;
											break;
									}
								}
							}
						}
					}
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.ToString(), &quot;Error&quot;, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}
	}

Current Output:
[![enter image description here][1]][1]

When I clicked on DataGridView, I get Output as follows:
[![enter image description here][2]][2]

Expected output:
[![enter image description here](https://i.stack.imgur.com/JTIk6.png)](https://i.stack.imgur.com/JTIk6.png)



Grouped DataGridView (it&#39;s works)
 
	namespace WinFormsApp1
	{
		public partial class CtechGroupedDataGridView : DataGridView
		{
			public CtechGroupedDataGridView()
			{
				InitializeComponent();

				DoubleBuffered = true;
				GridColor = Color.LightGray;
				BackgroundColor = SystemColors.Control;
				BorderStyle = BorderStyle.None;
				SelectionMode = DataGridViewSelectionMode.FullRowSelect;
				ColumnGroupEnabled = new int[] { 1, 2};

				ClearSelection();
			}

			protected override void OnDataBindingComplete(DataGridViewBindingCompleteEventArgs e)
			{
				base.OnDataBindingComplete(e);

				// Fit columns
				int columnsWidth = 0;
				foreach (DataGridViewColumn column in this.Columns)
				{
					if (column.Visible)
					{
						columnsWidth += column.Width;
					}
				}

				if (columnsWidth &lt; this.Width)
				{
					for (int i = 0; i &lt; this.Columns.Count; i++)
					{
						this.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
					}
					this.Columns[this.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
				}
				else
				{
					for (int i = 0; i &lt; this.Columns.Count; i++)
					{
						this.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
					}
				}

				for (int i = 0; i &lt; this.Columns.Count; i++)
				{
					int column = this.Columns[i].Width;
					this.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
					this.Columns[i].Width = column;
					this.Columns[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
				}

				ClearSelection();
			}


			protected override void OnCellFormatting(DataGridViewCellFormattingEventArgs args)
			{
				// Call home to base
				base.OnCellFormatting(args);

				// First row always displays
				if (args.RowIndex == 0)
				{
					return;
				}

				if (IsRepeatedCellValue(args.RowIndex, args.ColumnIndex))
				{
					args.Value = string.Empty;
					args.FormattingApplied = true;
				}
			}

			private bool IsRepeatedCellValue(int rowIndex, int colIndex)
			{
				if (ColumnGroupEnabled.Contains(colIndex))
				{
					DataGridViewCell currCell = Rows[rowIndex].Cells[colIndex];
					DataGridViewCell prevCell = Rows[rowIndex - 1].Cells[colIndex];

					if (currCell.Value != null &amp;&amp; prevCell.Value != null)
					{
						if ((currCell.Value == prevCell.Value) || (currCell.Value.ToString() == prevCell.Value.ToString()))
						{
							return true;
						}
					}
				}
				return false;
			}

			public int[] ColumnGroupEnabled { get; set; }


			protected override void OnCellPainting(DataGridViewCellPaintingEventArgs args)
			{
				base.OnCellPainting(args);

				// Keep first and last row to visible
				if (args.RowIndex &gt;= 0 &amp;&amp; args.RowIndex &lt; RowCount - 1)
				{
					args.AdvancedBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.None;
				}

				// Ignore column and row headers and first row
				if (args.RowIndex &lt; 1 || args.ColumnIndex &lt; 0)
				{
					return;
				}

				if (IsRepeatedCellValue(args.RowIndex, args.ColumnIndex))
				{
					args.AdvancedBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.None;
				}
				else
				{
					args.AdvancedBorderStyle.Top = AdvancedCellBorderStyle.Top;
				}
			}
		}
	}


Reguler DiscountModel (it&#39;s works)

    public class RegulerDiscountModel
    {
        public RegulerDiscountModel()
        {
        }

        [DisplayName(&quot;ID&quot;)]
        public int RegulerDiscountID
        {
            get; set;
        }

        [DisplayName(&quot;Product Id&quot;)]
        public int RegulerDiscountProductId
        {
            get; set;
        }

        [DisplayName(&quot;Product Name&quot;)]
        public String? RegulerDiscountProductName
        {
            get; set;
        }

        [DisplayName(&quot;Discount Name&quot;)]
        public String? RegulerDiscountName
        {
            get; set;
        }

        [DisplayName(&quot;Discount Value&quot;)]
        public double RegulerDiscountValue
        {
            get; set;
        }

        [DisplayName(&quot;Discount Type&quot;)]
        public String? RegulerDiscountStrTypeId
        {
            get; set;
        }
	}
	


  [1]: https://i.stack.imgur.com/qQjYs.png
  [2]: https://i.stack.imgur.com/ljrHY.png

</details>


# 答案1
**得分**: 0

以下是您提供的代码的翻译部分:

```csharp
private void CtechGroupedDataGridView_CellFormatting(object? sender, DataGridViewCellFormattingEventArgs e)
{
    try
    {
        if (e.RowIndex >= 0 && e.RowIndex <= CtechGroupedDataGridView.Rows.Count - 1)
        {
            // 这里有一个错误
            //DataGridViewRow row = CtechGroupedDataGridView.CurrentRow;
            DataGridViewRow row = CtechGroupedDataGridView[e.ColumnIndex, e.RowIndex].OwningRow;

            if (row != null)
            {
                // ID ProductId ProductName DiscountName DiscountValue DiscountType
                // 0  1         2           3            4             5

                if (row.Cells[4].Value != null && row.Cells[5].Value != null)
                {
                    String? strDiscountValue = row.Cells[4].Value.ToString();
                    String? strDiscountType = row.Cells[5].Value.ToString();
                    if (!String.IsNullOrEmpty(strDiscountValue) && !String.IsNullOrEmpty(strDiscountType))
                    {
                        switch (strDiscountType)
                        {
                            case "Rp":
                                CtechGroupedDataGridView[4, e.RowIndex].Style.Format = "N0";
                                break;

                            case "%":
                                // 这里有一个错误
                                //CtechGroupedDataGridView[4, e.RowIndex].Style.Format = "P1";
                                CtechGroupedDataGridView[4, e.RowIndex].Style.Format = "F1";
                                break;
                        }
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

希望这有助于您理解代码的翻译。

英文:
private void CtechGroupedDataGridView_CellFormatting(object? sender, DataGridViewCellFormattingEventArgs e)
{
try
{
if (e.RowIndex &gt;= 0 &amp;&amp; e.RowIndex &lt;= CtechGroupedDataGridView.Rows.Count - 1)
{
// Bug in here
//DataGridViewRow row = CtechGroupedDataGridView.CurrentRow;
DataGridViewRow row = CtechGroupedDataGridView[e.ColumnIndex, e.RowIndex].OwningRow;
if (row != null)
{
// ID ProductId ProductName DiscountName DiscountValue DiscountType
// 0  1         2           3            4             5
if (row.Cells[4].Value != null &amp;&amp; row.Cells[5].Value != null)
{
String? strDiscountValue = row.Cells[4].Value.ToString();
String? strDiscountType = row.Cells[5].Value.ToString();
if (!String.IsNullOrEmpty(strDiscountValue) &amp;&amp; !String.IsNullOrEmpty(strDiscountType))
{
switch (strDiscountType)
{
case &quot;Rp&quot;:
CtechGroupedDataGridView[4, e.RowIndex].Style.Format = &quot;N0&quot;;
break;
case &quot;%&quot;:
// Bug in here
//CtechGroupedDataGridView[4, e.RowIndex].Style.Format = &quot;P1&quot;;
CtechGroupedDataGridView[4, e.RowIndex].Style.Format = &quot;F1&quot;;
break;
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), &quot;Error&quot;, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

Output

Two different formats in the datagridview column

huangapple
  • 本文由 发表于 2023年5月26日 09:45:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76337175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定