Data insertion loop does not work - c#

Related to this question : I'm trying to write an "INSERT" loop : I have got the following query:
CommandText = "INSERT into sample2Prot(timestp,idq,idz,prot,Lhowmany,Rhowmany) VALUES(#timestp,#idq,#idz,#prot,#Lhowmany,#Rhowmany)";
When I execute my code (which can be found just below) I get the following error:
'#timestp' cannot be handle by SqlParameterCollection. ("timestp" = tableNames[0], of string type)
for (int j = 0; j < tableNames.Count; j++)
// tableNames contains the name of the columns, tableTypes the types of the columns
// tableTypes contains
{
if (tableTypes[j] == "INTEGER")
{
myCommand3.Parameters.Add("#" + tableNames[j], System.Data.SqlDbType.Int);
Console.WriteLine("#" + tableNames[j]);
}
else
{
myCommand3.Parameters.Add("#" + tableNames[j], System.Data.SqlDbType.VarChar);
Console.WriteLine("#" + tableNames[j]);
}
}
Console.WriteLine(myCommand3.CommandText);
for (int f = 0; f < total.Count(); f++)
{
for (int k = 0; k < tableNames.Count; k++)
{
myCommand3.Parameters.Clear();
myCommand3.Parameters["#" + tableNames[k]].Value = total[f][k];
}
myCommand3.ExecuteNonQuery();
}
Has someone an idea ? Don't mind asking for more precision.

for (int f = 0; f < total.Count(); f++)
{
for (int k = 0; k < tableNames.Count; k++)
{
myCommand3.Parameters.Clear(); // < ==== PROBLEM is here!
// After clearing the Parameters, there is no Parameter "["#" + tableNames[k]]"
// hence "SqlParameter mit ParameterName '#timestp' ist nicht in SqlParameterCollection enthalten."
// (eng: SqlParameterCollection does not contain SqlParameter with name '#timestp' )
myCommand3.Parameters["#" + tableNames[k]].Value = total[f][k];
}
myCommand3.ExecuteNonQuery();
}
In above code, move the Clear() statement like so:
for (int f = 0; f < total.Count(); f++)
{
for (int k = 0; k < tableNames.Count; k++)
{
myCommand3.Parameters["#" + tableNames[k]].Value = total[f][k];
}
myCommand3.ExecuteNonQuery();
}
myCommand3.Parameters.Clear();

Related

How to remove an element from an array and resize the array

I want to remove a specific object from an array, put it in a smaller array without getting out of range. This is what I've tried but it won't work.
Skateboard[] newSkateboard = new Skateboard[_skateboards.Length - 1];
for (int i = 0; i < _skateboards.Length; i++)
{
if (skateboard.Code != _skateboards[i].Code)
{
newSkateboard[i] = _skateboards[i];
}
}
Sure.
var j = 0;
for (int i = 0; i < _skateboards.Length; i++)
{
if (skateboard.Code != _skateboards[i].Code)
{
newSkateboard[j] = _skateboards[i];
j = j + 1;
}
}

NullReferenceException in child class when referring to member of parent [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
Pretty much the title. I first set it in the first method and as soon as I wanna call it up it says it´s empty. Even in the Inspector it says that it´s set to the right thing but it can´t be called for some reason.
The two relevant code snippets:
public class WUZ_Unit : Leader
{
public override void UpdatePosition()
{
vecPos = GameObject.Find("WUZ(Clone)").transform.position;
Debug.Log(this + " the grid: " + grid);
**position = grid.GetNode((int)vecPos.x, (int)vecPos.y);**
}
}
and:
public abstract class Entity : MonoBehaviour {
public void InitiateGrid(Gridmanager g)
{
anim = GetComponent<Animator>();
if (anim.gameObject.activeSelf)
{
anim.SetBool("IsAlive", true);
}
grid = g;
Debug.Log(this + " set " + grid);
}
}
what the console spits out on the first Debug Log:
and what the console spits out on the second Debug Log:
This is the Error Code in Text:
NullReferenceException: Object reference not set to an instance of an object
WUZ_Unit.UpdatePosition () (at Assets/Scripts/Unit/WUZ_Unit.cs:21)
GameHandler.UpdateAllMoves () (at Assets/Scripts/GameHandler.cs:1805)
GameHandler.Start () (at Assets/Scripts/GameHandler.cs:1697)
The asked for code regarding instantiation:
public void GenerateCharacters(int x, int y, GameObject c, int i)
{
GameObject go = Instantiate(c) as GameObject;
//Entity e = go.GetComponent<Entity>();
//StartCoroutine(e.SpawnAnim());
if (i == 0)
{
Unit u = go.GetComponent<Unit>();
go.GetComponent<Enemy>().enabled = false;
u.enabled = true;
u.InitializeUnits();
u.healthBarEnemy = healthBarEnemy;
u.healthBarAlly = healthBarAlly;
u.healthMeter = healthbarMeter;
u.highlightAttack = highlightAttack;
u.highlightIndicator = highlightIndicator;
u.highlightMove = highlightMove;
u.InitiateGrid(grid);
u.SetPos(x, y);
GeneratePosition(u, x, y);
u.PlayerChange(gamePhase);
go.GetComponent<Enemy>().enabled = false;
}
This is the asked for code regarding updateposition:
public void UpdateAllMoves()
{
Debug.Log("updating all moves");
//Updating the grid status
grid.UpdatePosition();
Unit[] ul = unitList.ToArray();
for (int i = 0; i < ul.Length; i++)
{
ul[i].UpdatePosition();
}
Enemy[] el = enemyList.ToArray();
for (int i = 0; i < el.Length; i++)
{
el[i].UpdatePosition();
}
CheckforCheckUnit(grid);
CheckforCheckEnemy(grid);
ConvertAllMoves();
grid.ClearNodeMoves();
grid.UpdatePosition();
UpdateNodes();
grid.UpdatePosition();
for (int i = 0; i < ul.Length; i++)
{
**ul[i].UpdatePosition();**
}
for (int i = 0; i < el.Length; i++)
{
el[i].UpdatePosition();
}
CheckforCheckUnit(grid);
CheckforCheckEnemy(grid);
ConvertAllMoves();
grid.ClearNodeMoves();
grid.UpdatePosition();
UpdateNodes();
}
so I made sure that vecPos is not the problem:
Debug.Log(this + " the grid: " + grid + " the vecPos " + vecPos.x + " " + vecPos.y);
What the console spits out:
WUZ (WUZ_Unit) the grid: the vecPos 2 28
UnityEngine.Debug:Log(Object)
WUZ_Unit:UpdatePosition() (at Assets/Scripts/Unit/WUZ_Unit.cs:20)
GameHandler:UpdateAllMoves() (at Assets/Scripts/GameHandler.cs:1805)
GameHandler:Start() (at Assets/Scripts/GameHandler.cs:1697)
more clarification code:
public void GettingCharacters()
{
Debug.Log(StaticPara.player1Units.Length);
for(int i = 0; StaticPara.player1Units.Length > i; i++)
{
unitList.Add(StaticPara.player1Units[i].GetComponent<Unit>());
int x = startingTilesBlue[i].xPos;
int y = startingTilesBlue[i].yPos;
GenerateCharacters(x, y, StaticPara.player1Units[i], 0);
}
for (int i = 0; StaticPara.player2Units.Length > i; i++)
{
enemyList.Add(StaticPara.player2Units[i].GetComponent<Enemy>());
int x = startingTilesRed[i].xPos;
int y = startingTilesRed[i].yPos;
GenerateCharacters(x, y, StaticPara.player2Units[i], 1);
}
}
void Start()
{
grid = gridGO.GetComponent<Gridmanager>();
grid.CreateGrid();
//setting up ui and the game
gamePhase = 0;
phaseStatusString = "Move Phase";
endPhaseButton.GetComponent<Button>().interactable = false;
ability_ALX = true;
//spawning character Models
GenerateStartingPositions();
GettingCharacters();
//Updating their stats
Unit[] ul = unitList.ToArray();
for (int i = 0; i < ul.Length; i++)
{
ul[i].healthMax = ul[i].healthBase;
ul[i].healthCurrent = ul[i].healthMax;
ul[i].damageCurrent = ul[i].damageBase;
}
Enemy[] el = enemyList.ToArray();
for (int i = 0; i < el.Length; i++)
{
el[i].healthMax = el[i].healthBase;
el[i].healthCurrent = el[i].healthMax;
el[i].damageCurrent = el[i].damageBase;
}
SelectKing();
**UpdateAllMoves();**
}
Here is the Update Nodes Function:
public void UpdateNodes()
{
for(int i = 0; i < unitList.Count; i++)
{
for(int j = 0; j < unitList[i].possibleMoves.Length; j++)
{
for(int k = 0; k < unitList[i].possibleMoves[j].Count; k++)
{
unitList[i].possibleMoves[j][k].moveableByUnit.Add(new CheckAssist(unitList[i], j));
}
}
for (int j = 0; j < unitList[i].possibleAttacks.Length; j++)
{
for (int k = 0; k < unitList[i].possibleAttacks[j].Count; k++)
{
unitList[i].possibleAttacks[j][k].attackableByUnit.Add(new CheckAssist(unitList[i], j));
}
}
for (int j = 0; j < unitList[i].possibleAttackIndicators.Length; j++)
{
for (int k = 0; k < unitList[i].possibleAttackIndicators[j].Count; k++)
{
unitList[i].possibleAttackIndicators[j][k].attackableByUnit.Add(new CheckAssist(unitList[i], j));
}
}
for (int j = 0; j < unitList[i].possibleAttacksInactive.Length; j++)
{
for (int k = 0; k < unitList[i].possibleAttacksInactive[j].Count; k++)
{
unitList[i].possibleAttacksInactive[j][k].passiveAAByUnit.Add(new CheckAssist(unitList[i], j));
}
}
}
for (int i = 0; i < enemyList.Count; i++)
{
for (int j = 0; j < enemyList[i].possibleMoves.Length; j++)
{
for (int k = 0; k < enemyList[i].possibleMoves[j].Count; k++)
{
enemyList[i].possibleMoves[j][k].moveableByEnemy.Add(new CheckAssist(enemyList[i], j));
}
}
for (int j = 0; j < enemyList[i].possibleAttacks.Length; j++)
{
for (int k = 0; k < enemyList[i].possibleAttacks[j].Count; k++)
{
enemyList[i].possibleAttacks[j][k].attackableByEnemy.Add(new CheckAssist(enemyList[i], j));
//Debug.Log("added attack to" + enemyList[i].possibleAttackIndicators[j][k].xPos + " " + enemyList[i].possibleAttackIndicators[j][k].yPos);
}
}
for (int j = 0; j < enemyList[i].possibleAttackIndicators.Length; j++)
{
for (int k = 0; k < enemyList[i].possibleAttackIndicators[j].Count; k++)
{
enemyList[i].possibleAttackIndicators[j][k].attackableByEnemy.Add(new CheckAssist(enemyList[i], j));
//Debug.Log("added attack to" + enemyList[i].possibleAttackIndicators[j][k].xPos + " " + enemyList[i].possibleAttackIndicators[j][k].yPos);
}
}
for (int j = 0; j < enemyList[i].possibleAttacksInactive.Length; j++)
{
for (int k = 0; k < enemyList[i].possibleAttacksInactive[j].Count; k++)
{
enemyList[i].possibleAttacksInactive[j][k].passiveAAByEnemy.Add(new CheckAssist(unitList[i], j));
}
}
}
}
The problem seems to be that some line among these:
CheckforCheckUnit(grid);
CheckforCheckEnemy(grid);
ConvertAllMoves();
grid.ClearNodeMoves();
grid.UpdatePosition();
UpdateNodes();
grid.UpdatePosition();
is modifying the Units in unitList in some way that sets the Unit.grid value to null.
Something else you might consider is adding GridManager as a parameter to UpdatePosition():
public override void UpdatePosition(GridManager gameGrid) {
vecPos = GameObject.Find("WUZ(Clone)").transform.position;
Debug.Log(this + " the grid: " + gameGrid);
position = gameGrid.GetNode((int)vecPos.x, (int)vecPos.y);
}
and then in UpdateAllMoves, include it in the calls. e.g.:
...
el[i].UpdatePosition(grid);
...
ul[i].UpdatePosition(grid);
...
I fixed my own Code and here is how:
unitList.Add(StaticPara.player1Units[i].GetComponent<Unit>());
int x = startingTilesBlue[i].xPos;
int y = startingTilesBlue[i].yPos;
GenerateCharacters(x, y, StaticPara.player1Units[i], 0);
I added the Unit script from the passed the GameObject rather than the Unit script from the instantiated Gameobject meaning I changed variables that were not even in the List
Thanks for all the help #ruzihm
EDIT: Yes I did I moved unitList.Add from GettingCharacters() to GenerateCharacters()

Check duplicate and sum values in datagridview c#

I'm coding like below but it works incorrect.It perform(plus and delete) only 2->3 rows if data has 5->6 duplicate data.
Update and It works
for (int i = 0; i < dataGridView1.RowCount - 1; i++) //compare data
{
var Row = dataGridView1.Rows[i];
string abc = Row.Cells[1].Value.ToString() + Row.Cells[2].Value.ToString().ToUpper();
// MessageBox.Show(abc);
for (int j = i + 1; j < dataGridView1.RowCount; j++)
{
var Row2 = dataGridView1.Rows[j];
string def = Row2.Cells[1].Value.ToString() + Row2.Cells[2].Value.ToString().ToUpper();
if (abc == def)
{
Row.Cells[5].Value = Convert.ToDouble(Row.Cells[5].Value.ToString()) + Convert.ToDouble(Row2.Cells[5].Value.ToString());
dataGridView1.Rows.Remove(Row2);
j--;
}
}
}
This should do the trick for you:
for (int i = 0; i < dataGridView1.RowCount - 1; i++) //compare data
{
var Row = dataGridView1.Rows[i];
string abc = Row.Cells[0].Value.ToString() + Row.Cells[1].Value.ToString().ToUpper();
for (int j = i+1; j < dataGridView1.RowCount; j++)
{
var Row2 = dataGridView1.Rows[j];
string def = Row2.Cells[0].Value.ToString() + Row2.Cells[1].Value.ToString().ToUpper();
if (abc == def)
{
Row.Cells[2].Value = (int)Row.Cells[2].Value + (int)Row2.Cells[2].Value;
dataGridView1.Rows.Remove(Row2);
j--;
}
}
}
You basically need to keep track of j variable as you remove rows from the collection.
If you're a fan of LINQ and don't mind a bit of a convoluted code, here is another approach:
for (int i = 0; i < dataGridView1.RowCount; i++) //compare data
{
var R = dataGridView1.Rows[i];
var V = R.Cells[0].Value.ToString() + R.Cells[1].Value.ToString().ToUpper();
var DupRows = dataGridView1.Rows.Cast<DataGridViewRow>().Skip(i + 1).
Where(r => r.Cells[0].Value.ToString() + r.Cells[1].Value.ToString().ToUpper() == V);
R.Cells[2].Value = (int)R.Cells[2].Value + DupRows.Sum(r => (int)r.Cells[2].Value);
foreach (var DupRow in DupRows)
DupRow.Tag = "Del";
}
for (int i = 0; i < dataGridView1.RowCount; i++)
{
var R = dataGridView1.Rows[i];
if (R.Tag?.ToString() == "Del")
{
dataGridView1.Rows.Remove(R);
i--;
}
}
As a word of advice, this kind of stuff is handled far more easily in the back-end. Whatever your DataGridView is bound to, be it a DataTable or a generic collection, you should implement duplicate removal there instead of directly playing with DataGridView cells.

Getting System.ArgumentOutOfRangeException while copy between two Datagridviews

If somebody could please help solve the following issue:
System.ArgumentOutOfRangeException : Index was out of range. Must be
non-negative and less than the size of the collection. Paarameter name
: index
The code:
for (int i = 0; i <= dataGridView2.Rows.Count ; i++)
{
for (int j = 0; j <= dataGridView3.Rows.Count; j++)
{
if (!string.IsNullOrEmpty(dataGridView2.Rows[i].Cells["supplier_name"].Value as string) && !string.IsNullOrEmpty(dataGridView3.Rows[j].Cells["brands_supplier"].Value as string))
{
if (dataGridView2.Rows[i].Cells["supplier_name"].Value.ToString() == dataGridView3.Rows[j].Cells["brands_supplier"].Value.ToString())
{
dataGridView2.Rows[i].Cells["brands_name"].Value += dataGridView3.Rows[j].Cells["brands_nume"].Value + " ";
}
}
else
{
break;
}
}
}
You try to access an element of your datagrid which doesn't exist.
You have to set your for condition to
for (int i = 0; i < dataGridView2.Rows.Count ; i++)
and
for (int j = 0; j < dataGridView3.Rows.Count; j++)
don't use <= because the index of dataGridView.Rows[] is 0 based.
For example, if your datagrid contains 3 elements you can reach them with:
var row1 = dataGrid.Rows[0]
var row2 = dataGrid.Rows[1]
var row3 = dataGrid.Rows[2]
And you try to access
var row4 = dataGrid.Rows[3] // Error because this item doesn't exist (System.ArgumentOutOfRangeException)
also, but this item doesn't exist
I think problem in cycle
for (int i = 0; i <= dataGridView2.Rows.Count ; i++)
You run one more time
use
for (int i = 0; i < dataGridView2.Rows.Count ; i++)

C# How to Print 2 arrays together

Ok, so lets say i have two arrays like these;
int[] wow = new int[50];
for (int j = 0; j < wow.Length; j++)
{
wow[j] = j + 1;
}
int[] wew = new int[50];
for (int i = 0; i < wew.Length; i++)
{
wew[i] = i + 10;
}
and i want to print them like;
1 , 11
2 , 12
3 , 13
for (int j = 0; j < wow.Length; j++)
{
wow1[j] = j + 1;
wow2[j] = j + 10;
//print wow1 & wow2 here.
Console.WriteLine("{0},{1}", wow1[j], wow2[j]);
}
Note that in your two loops, i is no different with j, they are essentially the same!
How about using two for-loops?
for(int i = 0; i < wow.Length;i++)
{
for(int j = 0; j < wew.Length;i++)
{
//Print
Console.WriteLine("{0} , {1}", wow[i].ToString(), wew[j].ToString());
}
}
Try this code in case both arrays are the same length
for (int i=0; i<wew.Length; i++)
{
Console.WriteLine(wow[i] + ", " + wew[i]);
}
If the length is different more logic is needed

Categories