object references not set to an instance of the object - c#

Am running asp.net application with c#.Am using gridview to update and delete the columns.deleting is working fine.if am clicking the update button i got
System.NullReferenceException: Object reference not set to an instance of an object.
My code is;
protected bool IsRowModified(GridViewRow row)
{
int currentID;
string currentName;
string currentLocation;
currentID = Convert.ToInt32(GridView1.DataKeys
[row.RowIndex].Value);
currentName = ((TextBox)row.FindControl
("txtName")).Text;
currentLocation = ((TextBox)row.FindControl
("txtLocation")).Text;
**System.Data.DataRow newRow = originalTable.Select
(String.Format("ID = {0}", currentID))[0];** //got error in this line
if (!currentName.Equals(newRow["Name"].ToString()))
{ return true; }
if (!currentLocation.Equals(newRow["Location"].ToString()))
{ return true; }
return false;
}

Either originalTable is null, or originalTable.Select(...) is returning null.
Could it be that you've deleted the underlying data from originalTable and not updated the UI?
An alternative method might be to use the DataItem property of the GridViewRow parameter:
protected bool IsRowModified(GridViewRow row)
{
string currentName = ((TextBox)row.FindControl("txtName")).Text;
string currentLocation = ((TextBox)row.FindControl("txtLocation")).Text;
DataRow newRow = (DataRow)row.DataItem;
if (!string.Equals(currentName, newRow["Name"].ToString()))
{
return true;
}
if (!string.Equals(currentLocation, newRow["Location"].ToString()))
{
return true;
}
return false;
}

My guess is that your currentID variable is null or empty. You should check your values for null or empty before you try to use them.
if(!String.IsNullOrEmpty(currentID))
{
// Continue processing
}

Related

How avoid error when get null from datagraidview

Here I need to avoid null from datagridview (winform)
private void SendUpdate()
{
if ((string)dataGridView1.SelectedRows[0].Cells[0].Value != string.Empty )
{
if (1 == dataGridView1.SelectedRows.Count)
{
int Id = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[0].Value);
Update up = new Update();
up.AssignValue(Id);
up.textBox1.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
up.comboBox1.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
up.textBox2.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
up.textBox3.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
up.textBox4.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
up.textBox5.Text = dataGridView1.SelectedRows[0].Cells[6].Value.ToString();
up.ShowDialog();
}
else
{
MessageBox.Show("Please Select the Single Data Which Required to Update");
}
}
else
{
MessageBox.Show("You Select the empty Row");
}
}
I had try !=string.empty; , !=null; , !="";
but error not solved.
1 == dataGridView1.SelectedRows.Count it true
But
(string)dataGridView1.SelectedRows[0].Cells[0].Value have null value
Show error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Windows.Forms.DataGridViewCell.Value.get returned null.
https://stackoverflow.com/a/32390609/9543244
private void SendUpdate()
{
if (String.IsNullOrWhiteSpace(dataGridView1.SelectedRows[0].Cells[0].Value as string))
{
MessageBox.Show("You Select the empty Row");
}
}
is not working
it eliminate all even row haveing data

RowUpdating Not working showing me input string is not in correct format

protected void gv_card_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int result = 0;
CreditCard prod = new CreditCard();
GridViewRow row = gv_card.Rows[e.RowIndex];
string id = gv_card.DataKeys[e.RowIndex].Value.ToString();
string tid = ((TextBox)row.Cells[0].Controls[0]).Text;
string tnumber = ((TextBox)row.Cells[1].Controls[0]).Text;
string texpirydate = ((TextBox)row.Cells[2].Controls[0]).Text;
string tcvv = ((TextBox)row.Cells[3].Controls[0]).Text;
string tcardtype = ((TextBox)row.Cells[4].Controls[0]).Text;
string tholdername = ((TextBox)row.Cells[5].Controls[0]).Text;
result = prod.CardUpdate(int.Parse(tid), tholdername, tnumber,texpirydate, int.Parse(tcvv), tcardtype );
if (result > 0)
{
Response.Write("<script>alert('Product updated successfully');</script>");
}
else
{
Response.Write("<script>alert('Product NOT updated');</script>");
}
gv_card.EditIndex = -1;
bind();
}
}
Above is my Code but it just cant seem to update my gridview
That message is likely coming from your call to int.Parse(string), which expects the string to be a valid integer. To handle this, you can instead use int.TryParse(string, out int), which will return true or false if it is able to parse the string. If it's successful, the out parameter will contain the parsed integer value.
So you would first try to parse the integer fields. If that fails you could return an error message, and if it succeeds then you can use the integers directly in your call to CardUpdate:
int tidValue;
int tcvvValue;
if (!int.TryParse(tid, out tidValue))
{
Response.Write("<script>alert('The value specified for TID is not an integer.');</script>");
}
else if (!int.TryParse(tcvv, out tcvvValue))
{
Response.Write("<script>alert('The value specified for TCVV is not an integer.');</script>");
}
else
{
result = prod.CardUpdate(tidValue, tholdername, tnumber, texpirydate, tcvvValue, tcardtype);
if (result > 0)
{
Response.Write("<script>alert('Product updated successfully');</script>");
}
else
{
Response.Write("<script>alert('Product NOT updated');</script>");
}
}

Null Reference Exception when trying to store an array

So I'm trying to store fields from a text file into an array. But when I reach the line
data = record.Trim().Split('*');
I get an error saying "Object reference not set to an instance of an object."
public bool matchCustomer(string accountID, string record)
{
String[] data = new String[5];
data = null;
data = record.Trim().Split('*');
this.accountNumber = data[0];
if (accountID == this.accountNumber)
{
return true;
}
else
{
return false;
}
}
Here is where the method is called:
public bool findCustomer(string accountNumber)
{
string record = Global.currentFile.getNextRecord(ref endOfFile);
bool okay = Global.customer.matchCustomer(accountNumber, record);
return okay;
}
Here is getNextRecord:
public string getNextRecord(ref Boolean endOfFileFlag)
{
string nextRecord;
endOfFileFlag = false;
nextRecord = reader.ReadLine();
if (nextRecord == null)
{
endOfFileFlag = true;
}
else
{
recordReadCount += 1;
} // end if
return (nextRecord);
} // end getNextRecord
First, you can simplify your code by replacing:
String[] data = new String[5];
data = null;
data = record.Trim().Split('*');
with just a single line:
string[] data = record.Trim().Split('*');
This is a correct statement, because you don't know the max index (elements) of the string[] array returning by Split() function.
Second, make sure that record!=null, and also it has a string containing "*" characters used as delimiter in Split() function.
Let's look at this line of code
data = record.Trim().Split('*');
If a NullReferenceException occurred here, that means you must be calling a method on a null object. In this case, the only possible object is record.
Now we know what is null, but why is it null? Let's look at this method:
public bool findCustomer(string accountNumber)
{
string record = Global.currentFile.getNextRecord(ref endOfFile);
bool okay = Global.customer.matchCustomer(accountNumber, record);
return okay;
}
Apparently you are using the return value of getNextRecord to call matchCustomer. This means that getNextRecord must return be returning null! So let's find out why getNextRecord returns null:
public string getNextRecord(ref Boolean endOfFileFlag)
{
string nextRecord;
endOfFileFlag = false;
nextRecord = reader.ReadLine();
if (nextRecord == null)
{
endOfFileFlag = true;
}
else
{
recordReadCount += 1;
} // end if
return (nextRecord);
} // end getNextRecord
If the method return nextRecord, that means nextRecord is null. And how did you get nextRecord? reader.ReadLine!
So the ultimate reason why record is null is that reader.ReadLine is null.
To avoid this exception, you need to first check whether record is null, then call the method on it:
if (record != null) {
data = record.Trim().Split('*');
} else {
// do other stuff
}
In C# 6, this can be simplified to
data = record?.Trim().Split('*');
If record is null, data will be null too!
Also, note that this code is redundant:
String[] data = new String[5];
data = null;
You are creating a bunch of strings and then setting the array to null. What's the point? So you can just remove that, and change the next line to:
string[] data = record?.Trim().Split('*');

Issue with checking if ID in class has changed

I have a class called Line that stores bunch of information including the ID of the Line(I have a list of lines). I am writing this information in a CSV file and I want to check if the first character of my ID has changed (hopefully to a greater number). This change signifies a new folder.
Here is what I have tried:
public bool IsNewFile (Line ln)
{
int newID = ln.getID()[0];
int oldID = 0;
if (newID != oldID)
{
oldID = newID;
return true;
}
else
{
oldID = newID;
return false;
}
}
Here is my store to csv method:
public void csvWriter (Line ln, StreamWriter stream)//Writes List to CSV
{
//some code here
if (IsNewFile(ln))
{
//MAGICAL LINE
}
else
{
//NOT MAGICAL LINE
}
stream.WriteLine(printLine);
}
here is getID()
public string getID()
{
return id;
}
With the current code I print MAGICAL LINE every time! What am I doing wrong?
You're always checking if the newID is != 0 because you always initialize oldID to 0. You should store the oldID in your Line class because as of now, setting oldID = newID will do nothing as those variables will get destroyed when the function returns its boolean.
public bool IsNewFile (Line ln)
{
int newID = ln.getID()[0];
int oldID = ln.getOldID()[0];
if (newID != oldID)
{
ln.oldID = newID;
return true;
}
else
{
ln.oldID = newID;
return false;
}
}
I'm not sure you are giving us enough information but oldID is always 0. You need to store oldID and compare it to newID somewhere.

C#: Selecting a row in DataGridView with parameters

I am having a DataGridView and an Add New Entry button. Each time I add a new entry to the database, I want the program to select the row of the new entry in the DataGridView. After clicking on the Add New Entry button, the below function will be called, with parameters of studentName and date passed to the function. The name of the DataGridView is dvgPontengHistory.
But there is an exception thrown:
Object reference not set to an instance of an object.
on this line:
if(r.Cells["student_name"].Value.ToString().Contains(studentName))
Below is the code:
private void selectRow(string studentName, string date)
{
int i = 0;
foreach (DataGridViewRow r in dgvPontengHistory.Rows)
{
if(r.Cells["student_name"].Value.ToString().Contains(studentName)) // error in this line
{
if (r.Cells["date"].Value.ToString().Contains(date))
{
dgvPontengHistory.Rows[i].Selected = true;
return;
}
}
i++;
}
}
Any tips on resolving this problem? Thanks.
Probably the case that student_name was null in on of the rows in the result set. That would cause ToString() to fail.
My guess is your update statement is putting null into your table.
Here is how you test:
(set breakpoints on the throw lines).
private void selectRow(string studentName, string date)
{
int i = 0;
foreach (DataGridViewRow r in dgvPontengHistory.Rows)
{
if (r.Cells["student_name"] == null) { throw("can't find cell"); }
if(r.Cells["student_name"].Value == null) { throw("cell has no value"); }
if(r.Cells["student_name"].Value.ToString().Contains(studentName)) // error in this line
{
if (r.Cells["date"].Value.ToString().Contains(date))
{
dgvPontengHistory.Rows[i].Selected = true;
return;
}
}
i++;
}
}
private void selectRow(string studentName, string date)
{
int i = 0;
foreach (DataGridViewRow r in dgvPontengHistory.Rows)
{
if(r.Cells["student_name"].Value == null) return;
if(r.Cells["student_name"].Value.ToString().Contains(studentName)) // error in this line
{
if (r.Cells["date"].Value.ToString().Contains(date))
{
dgvPontengHistory.Rows[i].Selected = true;
return;
}
}
i++;
}
}

Categories

Resources