I use these following code to calculating summation of a specific row in the database and show it in a new row under that intention column. but i will encounter an error.
Object reference not set to an instance of an object
Please help me to solve this.
Thanks in advance.
int sum = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
sum += int.Parse(dataGridView1.Rows[i].Cells["Fee"].Value.ToString());
}
DataSet ds = new DataSet();
adapter.Fill(ds);
DataRow row = ds.Tables["Entry"].NewRow();
ds.Tables["Entry"].Rows.Add(row);
I want to know how can I see the sum in a new row.
i think the error is in the loop statement:
Instead of:
for (int i = 0; i < dt.Rows.Count; i++)
{
sum += int.Parse(dataGridView1.Rows[i].Cells["Fee"].Value.ToString());
}
use this:
for (int i = 0; i < dt.Rows.Count - 1; i++)
{
sum += int.Parse(dataGridView1.Rows[i].Cells["Fee"].Value.ToString());
}
you are starting at Index zero so you should deduct one for the total number of rows. It will return Object reference not set to an instance of an object when it reaches on:
sum += int.Parse(dataGridView1.Rows[dt.Rows.Count].Cells["Fee"].Value.ToString());
because such row does not exists.
UPDATE 1
after the loop, insert this statement:
dataGridView1.Rows.Add("", "", sum)
UPDATE 2
int sum = 0;
for (int i = 0; i < dt.Rows.Count - 1; i++)
{
sum += int.Parse(dataGridView1.Rows[i].Cells["Fee"].Value.ToString());
}
DataSet ds = new DataSet();
adapter.Fill(ds);
DataRow row = ds.Tables["Entry"].NewRow();
row[0] = "";
row[1] = "";
row[2] = sum;
ds.Tables["Entry"].Rows.Add(row);
'ds' doesn't have a table 'Entry', that's why you get a 'Object reference not set to an instance of an object' error.
you can use compute method in datatable. get result from compute method then create new row from datatable then assign to appropriate field. then add the new row to datatable.
Though your question is not very clear but Check out the loop either access value from datatable or from grid
Like
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["Fee"].Value !=null)
sum += int.Parse(dt.Rows[i]["Fee"].Value.ToString());
}
And also make sure dt.Rows[i]["Fee"] does not contain null values
Even you can use Compute method to do the sum.
I suggest you to use the debugger and see where exactly this error occurs :)
It can also happen if the DB returns null for one "FEE" cell.
Run it and see where are you exactly and look at the values, if you see a null you'll need if != null.
Related
I'm trying to get a selected datagridview row to a datatable.
With the following code I am able to send the selectedrow over, however when trying to send a second row to the datatable, it adds an empty row but overwrites the first row in the datatable.
for (int i = 0; i < dataGridview.SelectedRows.Count; i++)
{
DT1.Rows.Add();
for (int j = 0; j < dataGridview.Columns.Count; j++)
{
DT1.Rows[0][j] = dataGridview.SelectedRows[i].Cells[j].Value;
}
}
As expected it enters the row on index 0, so i tried the folowing to get to the last row
for (int j = 0; j < dataGridview.Columns.Count; j++)
{
int rowcount = DT1.Rows.Count;
DT1.Rows[rowcount][j] = dataGridview.SelectedRows[i].Cells[j].Value;
}
This gives me an error that the row does not exist, what should be the solution to add a second row instead of replacing?
You've got other problems in your code. Namely, if your user selects the same rows in different calls to this code, you will insert duplicates.
Fix rowcount, changing it to rowcount-1. Then review your design. Come up with an approach to prevent duplicate insertions (unless you really want that).
You have a problem in rowcount
Rowcount gives you total no of rows but rowindex always starts with 0
ie rowindex = rowcount-1
use this
for (int j = 0; j < dataGridview.Columns.Count; j++)
{
int rowcount = DT1.Rows.Count;
DT1.Rows[rowcount-1][j] = dataGridview.SelectedRows[i].Cells[j].Value;
}
DT1.Rows[i][j] = dataGridview.SelectedRows[i].Cells[j].Value,ToString();
Try this! Your outer loop is already keeping track of the rows in your tables so there's no need to mess with the row count.
I'm new to C# and I can't find an example of this anywhere (although I have seen similar examples but the casting was ToString, whereas in my case I want arrays of integers). I have a DataTable object,
DataTable results = dbCon.ExecuteQuery("my query");
int m = results.Rows.Count;
int n = results.Columns.Count;
I want a jagged array consisting of n one-dimensional arrays (each array being a column of the DataTable (results, in this case).
int[][] jagged = new int[n][];
for (int i = 0; i < n; i++)
{
jagged[i] = new int[m];
//var coli = results.Columns.Cast<Array>().Select(column => Convert.ToInt32(column)).ToArray();
//jagged[i] = coli;
}
I've tried a few things (for example what I commented out) but I'm quite stuck now.
If anyone knows how to do this, please post something! Thanks!
Also, to be more specific, I'd really like to use a function like the one NumPy provides to Python... dataSet = np.array(dataList).astype('float'). Double for loops are not in my best interest as my DataTable is large.
I think you also need to make the array of type object. The DataTable DataRow holds things of type object, therefore that is what you need to store them as in your jagged array.
I think this will work:
DataTable table = dbCon.ExecuteQuery("my query");
int rowCount = table.Rows.Count;
int colCount = table.Columns.Count;
object[][] objs = new object[colCount][];
for (int currentColumn = 0; currentColumn < colCount; currentColumn++)
{
objs[currentColumn] = new object[rowCount];
for (int currentRow = 0; currentRow < rowCount; currentRow++)
{
objs[currentColumn][currentRow] = table.Rows[currentRow][currentColumn];
}
}
I think, you already have this. Try:
results.Rows[rowIndex][columnIndex]
To get it into jagged array, you may go for simple for loop:
for (int i = 0; i < results.Rows.Count; i++)
{
for (int j = 0; j < results.Columns.Count; j++)
{
jagged[i][j] = results.Rows[i][j];
}
}
You can get what you want just using LINQ against the DataTable. For each column in the DataTable, you need to iterate over the rows and select that column. You need to call Cast() to Select() on the columns and AsEnumerable() to be able to Select() on the rows:
int[][] jagged = results.Columns.Cast<DataColumn>()
.Select(
col => results.AsEnumerable()
.Select(row => row.Field<int>(col))
.ToArray()
).ToArray();
I want to insert datarow value in datatable particular row. Am having a datatable with values and then i want to overwrite the particular row value using c#.
my partial code id here:
for (int j = 0; j < DT.Rows.Count; j++)
{
row = DT2.NewRow();
row["Employee ID"] = Convert.ToString(DS.Rows[j]["fldempid"]);
row["Employee Name"] = Convert.ToString(DS.Rows[j]["fldempname"]);
string leavehstry = Convert.ToString(DS.Rows[j]["fldleavehistory"]);
string[] textarray1 = leavehstry.Split('-');
char[] delimiterChars1 = { ':' };
for (int i = 1; i <= textarray1.Length - 1; i++)
{
string[] words = textarray1[i - 1].Split(delimiterChars1);
string value = words[0].ToString();
string value1 = words[1].ToString();
row[value] = value1;
ivalue = i;
}
//DT2.Rows[j].Delete(); //I want to insert (or) overwrite the row value at j th position.
//DT2.Rows.Add(row);
//DT2.Rows[j].AcceptChanges();
}
please help me to insert it..
You can insert a DataRow in a DataTable at a specified index location by using the InsertAt method.
You might do this in place of your three commented out lines:
DT2.InsertAt(row, j);
If EmployerID is an unique value, then compare the DataColumn "EmployerID" value with EmployerID and Assign the datarow values as you want by using for loop.
I have come accross a strange problem that can be illustrated using the 2 seperate code blocks below.
If i use the first block, you can clearly see that column 5 has a currency format applied to it.
Using the second block where the only difference is that the string array is added to a datatable and then used as the datasource -> no formatting is applied!
Can anyone explain this behaivour and provide a workaround for me? I am using a large datatable that i will need to format.
Thanks!
Block 1:
string[] list = new string[10];
for (int i = 0; i < 10; i++)
{
list[i] = i.ToString();
}
this.dataGridViewX1.DataSource = list;
this.dataGridViewX1[0, 5].Style.Format = "C2";
Block 2:
string[] list = new string[10];
for (int i = 0; i < 10; i++)
{
list[i] = i.ToString();
}
DataTable dt = new DataTable();
dt.Columns.Add();
for (int i = 0; i < list.Length; i++)
{
DataRow dr = dt.NewRow();
dr[0] = list[i];
dt.Rows.Add(dr);
}
this.dataGridViewX1.DataSource = dt;
this.dataGridViewX1[0, 5].Style.Format = "C2";
Don't you need to set the DataColumn DataType?
DataColumn col1;
col1.DataType = Type.GetType("System.DateTime"); // or other type
the First One uses the datatables binding. use reflector to figure out what Happens there.
I have a grid view which contains 10 rows and 3 columns.. Now i want to loop through all rows and all columns of the gridview and want to add them to a datatable..
DataRow row;
int rowscount = gv.Rows.Count;
int columnscount = gv.Columns.Count;
for (int i = 0; i < rowscount; i++)
{
for (int j = 0; j < columnscount; j++)
{
row = empTable.NewRow();
row["a"] = gv.Rows[i][column1].Tostring();
row["b"] = gv.Rows[i][column2].ToString();
MynewDatatable.Rows.Add(row);
}
}
gv - my gridview
Now my question is , Can i get the value of all columns of all rows in gv to my new datatable.. I dont know whether my loop is correct or not... I am using this datatable for a bulkcopy function...
Your code above is creating a new Row for every cell in the GridView.
within each row of the GridView your code is assigning every value in the row to the same column, Emp_Name.
Corrected, I think:
int rowscount = gv.Rows.Count;
int columnscount = gv.Columns.Count;
for (int i = 0; i < rowscount; i++)
{
// Create the row outside the inner loop, only want a new table row for each GridView row
DataRow row = empTable.NewRow();
for (int j = 1; j < columnscount; j++)
{
// Referencing the column in the new row by number, starting from 0.
row[j - 1] = gv.Rows[i][j].Tostring();
}
MynewDatatable.Rows.Add(row);
}
EDIT: You've been editing the source in your question, so my answer may grow out-of-date. :)
Your loop is incorrect, all lists start at 0. But you start at 1 when looping through the columns.
The JMD answer is correct, but depending on your use-case, maybe databinding the DataSource of your grid view to your DataTable would be a better approach.
Try this code:
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
string selectedempid = dataGridView1.SelectedRows[0].Cells["Deptno"].Value.ToString();
{
SqlCommand cmd = new SqlCommand("delete from Test_dept where Deptno=" + selectedempid, con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
MessageBox.Show("deleted");
}
}