I am curently attempting to insert a int value into my datagridview progress bar ("Status" column) to define the percentage of bar filled (for example: inserting 7 would make a 7%/100% filled green bar in the progress bar cell). I have been struggling to define my input as I constantly get "System.InvalidCastException" whether I place the input in string format, int format or int32 format (ToString(), int.Parse(), and Int32.Parse()). Would love some guidance as to how to parse a value consistently into my progress bar, not sure what I am doing wrong here... The error seems to appear and disappear...
Inserting value into datatable/datagridview from list:
private void Textboxsheet_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = tableCollection[Textboxsheet.SelectedItem.ToString()];
dataGridView1.DataSource = dt;
if (dt != null)
{
List<Customer> customers = new List<Customer>();
for (int i = 0; i < dt.Rows.Count; i++)
{
Customer customer = new Customer();
customer.Store = dt.Rows[i]["a"].ToString();
customer.Product = dt.Rows[i]["b"].ToString();
customer.Size = dt.Rows[i]["c"].ToString();
customer.Proxy = dt.Rows[i]["d"].ToString();
customer.Status = Int32.Parse(dt.Rows[i]["Status"].ToString()); **#VALUE IN QUESTION**
customer.Actions = dt.Rows[i]["e"].ToString();
customers.Add(customer);
}
bindingSource1.DataSource = customers;
}
}
List, class file "Customer":
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp1
{
class Customer
{
public string a { get; set; }
public string b { get; set; }
public string c { get; set; }
public string d { get; set; }
public int Status { get; set; } **#variable in question**
public string e { get; set; }
public string f { get; set; }
public string g { get; set; }
}
}
Progress Bar code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;
namespace Sample
{
public class DataGridViewProgressColumn : DataGridViewImageColumn
{
public DataGridViewProgressColumn()
{
CellTemplate = new DataGridViewProgressCell();
}
}
}
namespace Sample
{
class DataGridViewProgressCell : DataGridViewImageCell
{
// Used to make custom cell consistent with a DataGridViewImageCell
static Image emptyImage;
static DataGridViewProgressCell()
{
emptyImage = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
}
public DataGridViewProgressCell()
{
this.ValueType = typeof(int);
}
// Method required to make the Progress Cell consistent with the default Image Cell.
// The default Image Cell assumes an Image as a value, although the value of the Progress Cell is an int.
protected override object GetFormattedValue(object value,
int rowIndex, ref DataGridViewCellStyle cellStyle,
TypeConverter valueTypeConverter,
TypeConverter formattedValueTypeConverter,
DataGridViewDataErrorContexts context)
{
return emptyImage;
}
protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
{
int progressVal = (int)value; **#ERROR THROWN HERE** **#ERROR THROWN HERE**
float percentage = ((float)progressVal / 100.0f); // Need to convert to float before division; otherwise C# returns int which is 0 for anything but 100%.
Brush backColorBrush = new SolidBrush(cellStyle.BackColor);
Brush foreColorBrush = new SolidBrush(cellStyle.ForeColor);
// Draws the cell grid
base.Paint(g, clipBounds, cellBounds,
rowIndex, cellState, value, formattedValue, errorText,
cellStyle, advancedBorderStyle, (paintParts & ~DataGridViewPaintParts.ContentForeground));
if (percentage > 0.0)
{
// Draw the progress bar and the text
g.FillRectangle(new SolidBrush(Color.FromArgb(0, 204, 0)), cellBounds.X + 2, cellBounds.Y + 2, Convert.ToInt32((percentage * cellBounds.Width - 4)), cellBounds.Height - 4);
g.DrawString(progressVal.ToString() + "%", cellStyle.Font, foreColorBrush, cellBounds.X + 6, cellBounds.Y + 2);
}
else
{
// draw the text
if (this.DataGridView.CurrentRow.Index == rowIndex)
g.DrawString(progressVal.ToString() + "%", cellStyle.Font, new SolidBrush(cellStyle.SelectionForeColor), cellBounds.X + 6, cellBounds.Y + 2);
else
g.DrawString(progressVal.ToString() + "%", cellStyle.Font, foreColorBrush, cellBounds.X + 6, cellBounds.Y + 2);
}
}
}
}
Exception:
System.InvalidCastException
HResult=0x80004002
Message=Specified cast is not valid.
Source=WindowsFormsApp1
StackTrace:
at Sample.DataGridViewProgressCell.Paint(Graphics g, Rectangle clipBounds, Rectangle cellBounds, Int32 rowIndex, DataGridViewElementStates cellState, Object value, Object formattedValue, String errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) in C:\Users\Win_10\source\repos\Localiteration\Localiteration\progressbar.cs:line 44
at System.Windows.Forms.DataGridViewCell.PaintWork(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, Int32 rowIndex, DataGridViewElementStates cellState, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
at System.Windows.Forms.DataGridViewRow.PaintCells(Graphics graphics, Rectangle clipBounds, Rectangle rowBounds, Int32 rowIndex, DataGridViewElementStates rowState, Boolean isFirstDisplayedRow, Boolean isLastVisibleRow, DataGridViewPaintParts paintParts)
at System.Windows.Forms.DataGridViewRow.Paint(Graphics graphics, Rectangle clipBounds, Rectangle rowBounds, Int32 rowIndex, DataGridViewElementStates rowState, Boolean isFirstDisplayedRow, Boolean isLastVisibleRow)
at System.Windows.Forms.DataGridView.PaintRows(Graphics g, Rectangle boundingRect, Rectangle clipRect, Boolean singleHorizontalBorderAdded)
at System.Windows.Forms.DataGridView.PaintGrid(Graphics g, Rectangle gridBounds, Rectangle clipRect, Boolean singleVerticalBorderAdded, Boolean singleHorizontalBorderAdded)
at System.Windows.Forms.DataGridView.OnPaint(PaintEventArgs e)
Debug("?value.GetType()"):
?value.GetType()
{Name = "Double" FullName = "System.Double"}
Assembly: {mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089}
AssemblyQualifiedName: "System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
Attributes: Public | SequentialLayout | Sealed | Serializable | BeforeFieldInit
BaseType: {Name = "ValueType" FullName = "System.ValueType"}
ContainsGenericParameters: false
CustomAttributes: Count = 3
DeclaredConstructors: {System.Reflection.ConstructorInfo[1]}
DeclaredEvents: {System.Reflection.EventInfo[0]}
DeclaredFields: {System.Reflection.FieldInfo[8]}
DeclaredMembers: {System.Reflection.MemberInfo[53]}
DeclaredMethods: {System.Reflection.MethodInfo[44]}
DeclaredNestedTypes: {System.Reflection.TypeInfo.<get_DeclaredNestedTypes>d__23}
DeclaredProperties: {System.Reflection.PropertyInfo[0]}
DeclaringMethod: '((System.RuntimeType)value.GetType()).DeclaringMethod' threw an exception of type 'System.InvalidOperationException'
DeclaringType: null
FullName: "System.Double"
GUID: {0f4f147f-4369-3388-8e4b-71e20c96f9ad}
GenericParameterAttributes: '((System.RuntimeType)value.GetType()).GenericParameterAttributes' threw an exception of type 'System.InvalidOperationException'
GenericParameterPosition: '((System.RuntimeType)value.GetType()).GenericParameterPosition' threw an exception of type 'System.InvalidOperationException'
GenericTypeArguments: {System.Type[0]}
GenericTypeParameters: {System.Type[0]}
HasElementType: false
ImplementedInterfaces: {System.Type[5]}
IsAbstract: false
IsAnsiClass: true
IsArray: false
IsAutoClass: false
IsAutoLayout: false
IsByRef: false
IsCOMObject: false
IsClass: false
IsConstructedGenericType: false
IsContextful: false
IsEnum: false
IsExplicitLayout: false
IsGenericParameter: false
IsGenericType: false
IsGenericTypeDefinition: false
IsImport: false
IsInterface: false
IsLayoutSequential: true
IsMarshalByRef: false
IsNested: false
IsNestedAssembly: false
IsNestedFamANDAssem: false
IsNestedFamORAssem: false
IsNestedFamily: false
IsNestedPrivate: false
IsNestedPublic: false
IsNotPublic: false
IsPointer: false
IsPrimitive: true
IsPublic: true
IsSealed: true
IsSecurityCritical: false
IsSecuritySafeCritical: false
IsSecurityTransparent: true
IsSerializable: true
IsSpecialName: false
IsUnicodeClass: false
IsValueType: true
IsVisible: true
MemberType: TypeInfo
MetadataToken: 33554647
Module (System.Reflection.MemberInfo): {CommonLanguageRuntimeLibrary}
Module: {CommonLanguageRuntimeLibrary}
Name: "Double"
Namespace: "System"
ReflectedType: null
StructLayoutAttribute: {System.Runtime.InteropServices.StructLayoutAttribute}
TypeHandle: {System.RuntimeTypeHandle}
TypeInitializer: {Void .cctor()}
UnderlyingSystemType: {Name = "Double" FullName = "System.Double"}
User contributions licensed under CC BY-SA 3.0