I am trying to make a billing software and want to merge the rows with same barcode with a press of a button, and if that row contains remark then the row should not merge.
private void button3_Click(object sender, EventArgs e)
{
int GROW = dataGridView1.RowCount;
for(int i=0; i<GROW; i++)
{
DataGridViewRow row= dataGridView1.Rows[i];
string A = row.Cells[0].Value.ToString();
for(int j = 0; j< GROW; j++)
{
if(j == i)
{
}
else
{
DataGridViewRow rowb= dataGridView1.Rows[j];
string B = rowb.Cells[0].Value.ToString();
if (A == B)
{
string rema = row.Cells[8].Value.ToString();
string remb = rowb.Cells[8].Value.ToString();
if(rema == "" && remb == "")
{
string qa = row.Cells[2].Value.ToString();
string qb = rowb.Cells[2].Value.ToString();
decimal qad = Convert.ToDecimal(qa);
decimal qbd = Convert.ToDecimal(qb);
decimal tqd = qad + qbd;
string ra = row.Cells[7].Value.ToString();
string rb = rowb.Cells[7].Value.ToString();
decimal rad = Convert.ToDecimal(ra);
decimal rbd = Convert.ToDecimal(rb);
decimal trd = rad + rbd;
row.Cells[7].Value = trd;
row.Cells[2].Value= tqd;
dataGridView1.Rows.RemoveAt(j);
// i = i - 1;
GROW--;
}
}
}
}
}
Assuming your value is in Cell[2] and remark in Cell[8], something like this should work:
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
int k = 0;
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
// Check if values are same but remarks are different
if (dataGridView1.Rows[i].Cells[2].Value == dataGridView1.Rows[j].Cells[2].Value && dataGridView1.Rows[i].Cells[8].Value != dataGridView1.Rows[j].Cells[8].Value)
{
if (k != 0)
{
items.Rows.RemoveAt(j);
dataGridView1.DataSource = items;
}
k++;
}
}
}
NOTE: I have not tested this code but I hope you get the idea
I'm a math student with little to no experience programming, but I wrote this to act like a brute force algorithm. It seems to run fine except that it runs all the password combinations out to 3 characters for passwords as short as 2. Also I'm sure there's a way to refactor the for and if statements as well. Any help would be appreciated, thanks.
I've already been testing to see if some of the if statements aren't executing, and it looks like the statements with "console.writeln(Is this executing)" aren't executing but I'm not really sure.
public Form1()
{
InitializeComponent();
}
static char[] Match ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j' ,'k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','C','L','M','N','O','P',
'Q','R','S','T','U','V','X','Y','Z','!','?',' ','*','-','+'};
private string[] tempPass;
private void button1_Click(object sender, EventArgs e)
{
string tempPass1 = "lm";
string result = String.Empty;
int passLength = 1;
int maxLength = 17;
tempPass = new string[passLength];
for (int i = 0; i < Match.Length; i++)
{
if (tempPass1 != result)
{
tempPass[0] = Match[i].ToString();
result = String.Concat(tempPass);
if (passLength > 1)
{
for (int j = 0; j < Match.Length; j++)
{
if (tempPass1 != result)
{
tempPass[1] = Match[j].ToString();
result = String.Concat(tempPass);
if (passLength > 2)
{
for (int k = 0; k < Match.Length; k++)
{
if (tempPass1 != result)
{
tempPass[2] = Match[k].ToString();
result = String.Concat(tempPass);
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass[2] == "+" && tempPass1 != result)
{
Console.WriteLine("This will execute?");
passLength++;
tempPass = new string[passLength];
k = 0;
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is big gay: " + result);
break;
}
}
}
}
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass1 != result)
{
Console.WriteLine("Did this execute?");
passLength++;
tempPass = new string[passLength];
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is bigger gay: " + result);
break;
}
}
}
}
//tempPass[1] = "World!";
//Console.WriteLine(result);
if (tempPass[tempPass.Length - 1] == "+" && tempPass1 != result)
{
passLength++;
tempPass = new string[passLength];
Console.WriteLine(tempPass.Length + " " + result + " " + "Success");
Console.WriteLine(i);
i = 0; /**update
j = 0;
k = 0;
l = 0;
m = 0;*/
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is biggest gay: " + result);
}
}
}
}
Play with this; modified from my answer here. It'll show you all the 2 and 3 length combinations. Clicking the button will start/stop the generation process. You need a button, label, and a timer:
public partial class Form1 : Form
{
private Revision rev;
public Form1()
{
InitializeComponent();
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
}
private void timer1_Tick(object sender, EventArgs e)
{
rev.NextRevision();
if (rev.CurrentRevision.Length == 4)
{
timer1.Stop();
MessageBox.Show("Sequence Complete");
// make it start back at the beginning?
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
else
{
label1.Text = rev.CurrentRevision;
}
}
}
public class Revision
{
private string chars;
private char[] values;
private System.Text.StringBuilder curRevision;
public Revision()
{
this.DefaultRevision();
}
public Revision(string validChars)
{
if (validChars.Length > 0)
{
chars = validChars;
values = validChars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
else
{
this.DefaultRevision();
}
}
public Revision(string validChars, string startingRevision)
: this(validChars)
{
curRevision = new System.Text.StringBuilder(startingRevision.ToUpper());
int i = 0;
for (i = 0; i <= curRevision.Length - 1; i++)
{
if (Array.IndexOf(values, curRevision[i]) == -1)
{
curRevision = new System.Text.StringBuilder(values[0]);
break;
}
}
}
private void DefaultRevision()
{
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
values = chars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
public string ValidChars
{
get { return chars; }
}
public string CurrentRevision
{
get { return curRevision.ToString(); }
}
public string NextRevision(int numRevisions = 1)
{
bool forward = (numRevisions > 0);
numRevisions = Math.Abs(numRevisions);
int i = 0;
for (i = 1; i <= numRevisions; i++)
{
if (forward)
{
this.Increment();
}
else
{
this.Decrement();
}
}
return this.CurrentRevision;
}
private void Increment()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index < (chars.Length - 1))
{
index = index + 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[0];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index < (values.Length - 1))
{
index = index + 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[0];
}
}
curRevision.Insert(0, values[0]);
}
}
private void Decrement()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[values.Length - 1];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[values.Length - 1];
}
}
curRevision.Remove(0, 1);
if (curRevision.Length == 0)
{
curRevision.Insert(0, values[0]);
}
}
}
}
I'm trying to implement KMP algorithm. Part "if (W[i] == S[m + i])" returns index out of range exception and I can't get it to work.
I was following example on Wikipedia: https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
static int[] KMPTable(string W)
{
int[] T = new int[W.Length];
int pos = 2;
int cnd = 0;
T[0] = -1;
T[1] = 0;
while (pos < W.Length)
{
if (W[pos - 1] == W[cnd])
{
T[pos] = cnd + 1;
cnd = cnd + 1;
pos = pos + 1;
}
else
if (cnd > 0)
{
cnd = T[cnd];
}
else
{
T[pos] = 0;
pos = pos + 1;
}
}
return T;
}
static int[] KMPSearch(string S, string W)
{
int m = 0;
int i = 0;
int[] kmpNext = KMPTable(S);
List<int> result = new List<int>();
while (m + i < S.Length)
{
if (W[i] == S[m + i])
{
if (i == W.Length - 1)
{
result.Add(m);
}
i = i + 1;
}
else
{
m = m + i - kmpNext[i];
if (kmpNext[i] > -1)
i = kmpNext[i];
else
i = 0;
}
}
return result.ToArray();
}
When m + i < S.Length, then it might be W[i] that is out of its index. Try checking with a step-by-step debug.
I'm trying to create a basic weather app where you can enter readings for a city and it will display the average, lowest temperature and highest temperature.
I created a 2d array (intTemps) with 5 rows (citys) and 4 columns (4 readings). Whenever I add a temperature to the listbox, it always displays in the upper left. When I add another temperature, it displays the same temperature that was just displayed and the current temperature.
The code is based on an example my professor wrote, so I'm not sure why its not displaying right.
public partial class Form1 : Form
{
string[] strNames = { "Livonia",
"Redford" ,
"Novi" ,
"Westland",
"Northville" };
int[,] intTemps = new int[5, 4];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i <= 4; i++)
{
cobNames.Items.Add(strNames[i]);
lstNames.Items.Add(strNames[i]);
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (cobNames.SelectedIndex >= 0 && cobNames.SelectedIndex <= 4)
{
if (intTemps[cobNames.SelectedIndex, (int)nudTemp.Value - 1] == 0)
{
intTemps[cobNames.SelectedIndex, (int)nudTemp.Value - 1] = Int32.Parse(txtTemp.Text);
}
else
{
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
result = MessageBox.Show("Do you want to change temps?", "Temps already exist!", buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
intTemps[cobNames.SelectedIndex, (int)nudTemp.Value - 1] = Int32.Parse(txtTemp.Text);
}
}
displayTemps();
}
else
{
MessageBox.Show("You must select a valid name!");
}
}
catch (FormatException)
{
MessageBox.Show("Temps must be integers");
}
}
private void displayTemps()
{
string strLine;
lstTemp.Items.Clear();
double[] dblAverages = new double[5];
int intNonBlank = 0;
for (int l = 0; l <= 4; l++)
{
intNonBlank = 0;
for (int c = 0; c <= 3; c++)
{
if (intTemps[l, c] != 0)
{
dblAverages[l] += intTemps[l, c];
intNonBlank++;
}
}
if (intNonBlank != 0)
{
dblAverages[l] /= intNonBlank;
}
}
for (int l = 0; l <= 4; l++)
{
strLine = " ";
for (int c = 0; c <= 3; c++)
{
if (intTemps[l, c] == 0)
{
strLine += " ";
}
else
{
if (intTemps[l, c] == 120)
{
strLine += intTemps[l, c] + " ";
}
else
{
strLine += intTemps[l, c] + " ";
}
lstTemp.Items.Add(strLine);
}
}
}
}
}
I rewrite your displayTemps() procedure. This wil add to lstTemp all information you need:
private void displayTemps()
{
string strLine;
lstTemp.Items.Clear();
double[] dblAverages = new double[5];
int intNonBlank = 0;
for (int l = 0; l <= 4; l++)
{
intNonBlank = 0;
for (int c = 0; c <= 3; c++)
{
if (intTemps[l, c] != 0)
{
dblAverages[l] += intTemps[l, c];
intNonBlank++;
}
}
if (intNonBlank != 0)
{
dblAverages[l] /= intNonBlank;
}
int min_temp = System.Linq.Enumerable.Range(0, 4).
Select(i => intTemps[l, i]).Min();
int max_temp = System.Linq.Enumerable.Range(0, 4).
Select(i => intTemps[l, i]).Max();
lstTemp.Items.Add(
"Average temp for city "+ l +": " + dblAverages[l] + " " +
"Minimum " + min_temp + " " +
"Maximum " + max_temp);
}
}
Essentially I have to show rows of bars on a stacked bar chart. There will be one for each question. Optionally there will be an extra bar or two for each question if there's a National score or a Competitor score is available.
My issue is one of presentation. I wish to place the bars central relative to the label for the question or remove gaps if one of the national or competitor scores isn't present.
Perhaps a picture will help:
I put together an example quickly (that generated the above picture) into an MVC project. These are the files:
Index.cshtml
<h2>Attempt 2</h2>
<img src="/Home/StackedBar100" />
<h2>Attempt 1</h2>
<img src="/Home/StackedBar100_FirstAttempt" />
HomeController.cs
<!-- language: c# -->
public class HomeController : Controller
{
List<Color> colors = new List<Color>();
string[] rows = new string[] { "Q1", "Q2", "Q3", "Q4" };
string[] stackTypes = new string[] { "National", "Value", "Competitor" };
Color[] stackColors = new Color[] { Color.White, Color.Green, Color.Orange };
protected override void Initialize(RequestContext requestContext)
{
// Set up bands of colours for testing purposes.
int diff = (255 - 20) / 10;
for (int c = 10; c > 0; c--)
{
colors.Add(Color.FromArgb(0, (c * diff) + 10, 0));
}
base.Initialize(requestContext);
}
public ActionResult Index()
{
return View();
}
public ActionResult StackedBar100()
{
var chart = new Chart();
var chartArea = new ChartArea("Default");
chart.ChartAreas.Add(chartArea);
chart.Width = 640;
chart.Height = 480;
var r = new Random();
for (int s = 0; s < stackTypes.Count(); s++)
{
var stack = stackTypes[s];
var stackColor = stackColors[s];
{
for (int i = 1; i <= 10; i++)
{
var series = new Series(stack + i.ToString());
series.ChartType = SeriesChartType.StackedBar100;
series.Color = colors[i - 1];
series.BorderColor = stackColor;
series["StackedGroupName"] = stack;
series["DrawSideBySide"] = "true";
series.IsValueShownAsLabel = true;
series.LabelForeColor = Color.White;
chart.Series.Add(series);
}
}
}
var dt = CreateData();
foreach (DataRow row in dt.Rows)
{
var question = row["Question"];
var stack = row["Stack"];
var hidden = Convert.ToBoolean(row["Hidden"]);
var ks = "";
for (int k = 1; k <= 10; k++)
{
ks = k.ToString();
chart.Series[stack + ks].Points.AddXY(question, row[ks]);
if (hidden)
{
chart.Series[stack + ks].Points.Last().IsEmpty = true;
}
else if ((row[ks] as double?) < 3)
{
chart.Series[stack + ks].Points.Last().IsValueShownAsLabel = false;
}
}
}
return ReturnChartAsImage(chart);
}
private DataTable CreateData()
{
var r = new Random();
var dt = new DataTable("Chart Data");
dt.Columns.Add("Question", typeof(string));
dt.Columns.Add("Stack", typeof(string));
dt.Columns.Add("Hidden", typeof(string));
for (int i = 1; i <= 10; i++)
{
dt.Columns.Add(i.ToString(), typeof(double));
}
foreach (var row in rows.OrderByDescending(rw => rw))
{
foreach (var stack in stackTypes)
{
if (
(stack == "Value") && row != "Q4" ||
(stack == "National" && (row == "Q2" || row == "Q4")) ||
(stack == "Competitor" && (row == "Q3" || row == "Q4")))
{
var dr = dt.NewRow();
dr["Question"] = row;
dr["Hidden"] = false;
dr["Stack"] = stack;
for (int k = 1; k <= 10; k++)
{
dr[k.ToString()] = r.NextDouble() * 10;
}
dt.Rows.Add(dr);
}
else
{
var dr = dt.NewRow();
dr["Question"] = row;
dr["Stack"] = stack;
dr["Hidden"] = true;
dt.Rows.Add(dr);
}
}
}
dt.WriteXml(#"c:\Users\chris_000\Desktop\1.xml");
return dt;
}
public ActionResult StackedBar100_FirstAttempt()
{
var chart = new Chart();
var chartArea = new ChartArea("Default");
chart.ChartAreas.Add(chartArea);
chart.Width = 640;
chart.Height = 480;
for (int i = 1; i <= 30; i++)
{
var series = new Series("Series" + i.ToString());
series.ChartType = SeriesChartType.StackedBar100;
series.Color = colors[(i - 1) % 10];
if (i <= 10)
{
series["StackedGroupName"] = "Value";
}
else if (i > 10 && i <= 20)
{
series["StackedGroupName"] = "National";
series.BorderColor = Color.Green;
}
else
{
series["StackedGroupName"] = "Competitor";
series.BorderColor = Color.Orange;
}
chart.Series.Add(series);
}
var dt = CreateData_FirstAttempt();
foreach (DataRow row in dt.Rows)
{
var question = row["Question"];
var group = row["Stack"];
for (int k = 1; k <= 30; k++)
{
chart.Series["Series" + k.ToString()].Points.AddXY(question, row[k.ToString()]);
}
}
return ReturnChartAsImage(chart);
}
private DataTable CreateData_FirstAttempt()
{
var r = new Random();
var dt = new DataTable("Chart Data");
dt.Columns.Add("Question", typeof(string));
dt.Columns.Add("Stack", typeof(string)); // Value, National, Competitor
for (int i = 1; i <= 30; i++)
{
dt.Columns.Add(i.ToString(), typeof(double));
}
foreach (var row in rows.OrderByDescending(rw => rw))
{
var dr = dt.NewRow();
dr["Question"] = row;
dr["Stack"] = "Score";
for (int k = 1; k <= 30; k++)
{
if (k <= 10)
{
if (row != "Q4")
{
dr[k.ToString()] = r.NextDouble() * 100;
}
else
{
dr[k.ToString()] = DBNull.Value;
}
}
else if (k > 10 && k <= 20)
{
if (row == "Q2" || row == "Q4")
{
dr[k.ToString()] = r.NextDouble();
}
else
{
dr[k.ToString()] = DBNull.Value;
}
}
else
{
if (row == "Q3" || row == "Q4")
{
dr[k.ToString()] = r.NextDouble();
}
else
{
dr[k.ToString()] = DBNull.Value;
}
}
}
dt.Rows.Add(dr);
}
return dt;
}
private ActionResult ReturnChartAsImage(Chart chart)
{
MemoryStream ms = new MemoryStream();
chart.SaveImage(ms, ChartImageFormat.Png);
return File(ms.ToArray(), "image/png");
}
}
That's a long example, but shows two different attempts at building multiple bars on a stacked chart. One using 30 columns, but splitting every 10 for each group. The second (more sensible) naming the stacks after the Value, National or Competitor they're supposed to represent.
So, in short, can I collapse the space occupied but the missing series/bars? Is it the way I'm feeding the data in perhaps?
Thanks.