I am currently working with padding in C#. I am displaying results inside a multiline textbox. The problem is this line string result1 = string.Format(format, berries + " "); giving me the error Index (zero based) must be greater than or equal to zero and less than the size of the argument list. I am not sure how to fix that. how can i display the results with even padding in between?
CODE
namespace farm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public abstract class Plants
{
protected string the_name;
protected double num_stock;
protected double price_peritem;
protected double total_item_value;
public Plants(string new_name, int new_stock, double new_price)
{
the_name = new_name;
num_stock = new_stock;
price_peritem = new_price;
}
public override string ToString()
{
return "";
}
public virtual double Get_Value()
{
double s = 0;
return s;
}
}
public class Berries : Plants
{
string variety;
string months;
public Berries(string new_name, int new_stock, double new_price, string new_variety, string new_months)
: base(new_name, new_stock, new_price)
{
variety = new_variety;
months = new_months;
total_item_value = num_stock * price_peritem;
//total_value += total_item_value;
}
public override string ToString()
{
string s = "Berries" + " " + num_stock + " " + the_name + " " + price_peritem;
return s;
}
public override double Get_Value()
{
total_item_value = num_stock * price_peritem;
return total_item_value;
}
}
public void Report()
{
const string format = "{0,-25} {1,-25} {2,-25} {3,-25} {4,-25}";
Berries berries1 = new Berries("BlueBerries", 12, 5, "AAA Early", "July");
string result1 = string.Format(format, berries1 + " ");
textBox1.AppendText(result1 + Environment.NewLine);
Berries berries2 = new Berries("Strawberry", 12, 5, "FrostStar", "December");
string result = string.Format(format, berries2 + " ");
textBox1.AppendText(result + Environment.NewLine);
}
private void button1_Click(object sender, EventArgs e)
{
Report();
}
}
}
You should consider overloading
ToString()of Berries and then build the entire set of Berrie values usingStringBuilder. I think at the very base string.Format usesStringBuilderby overloading theToString() and usingStringBuilderit should be cleaner and more efficient.Now that I’ve had more time to look at your code…I can say my last answer is not it.
What you really want to do is follow data encapsulation. You override
ToString()in your base but you return an empty string. What would be better is to do your base formatting there, and then build on it from each child. I’ve hacked out vaguely what I am talking about. The code is below