Cannot looping DataGridView null values - c#

I'm trying to loop through the DataGridView rows and then send the values for an update in my SQL-DB. I can make the update, but the program crashes when I come to the end of the rows, because then it read a null-value.
Exception: System.NullReferenceException, Additional information: Object reference not set to an instance of an object.
I have two questions:
Why can't I stop the method with return (see below) with my if
statement?
How can I let the loop insert null values in the strings? Some of
my columns it's OK to send null-values to. And some not, is there
any way to choose which?
private void editEmployeeDGV()
{
foreach (DataGridViewRow row in employeeDataGridView.Rows)
{
if (row.Cells["SocialSNColumn"].Value.ToString() == null)
{
return;
}
string SocialSN = row.Cells["SocialSNColumn"].Value.ToString();
string Name = row.Cells["nameColumn"].Value.ToString();
string Surname = row.Cells["SurnameColumn"].Value.ToString();
string Email = row.Cells["EmailColumn"].Value.ToString();
string TelNr = row.Cells["TelNrColumn"].Value.ToString();
string Gender = row.Cells["GenderColumn"].Value.ToString();
string ECName = row.Cells["ECNameColumn"].Value.ToString();
string ECNumber = row.Cells["ECNumberColumn"].Value.ToString();
cont.editEmployeeDGV(SocialSN, Name, Surname, Email, TelNr, Gender, ECName, ECNumber);
}
}

The reason for the exception is that you're trying to call the ToString() method on the Value property, but it's null.
if (row.Cells["SocialSNColumn"].Value.ToString() == null)
{
return;
}
There's no reason to cast to a string first; just test for null:
if (row.Cells["SocialSNColumn"].Value == null)
{
return;
}
Your other lines of code run the same risk of throwing an NRE if any of their Value properties are null. To avoid those, you may want to replace ToString() with the Convert.ToString() method, which replaces null with an empty string:
string SocialSN = Convert.ToString(row.Cells["SocialSNColumn"].Value);
string Name = Convert.ToString(row.Cells["nameColumn"].Value);

Related

Do not return error since i expect null

Here i have example of getting inventory from json string.
inventory = JsonUtility.FromJson<InventoryModel>GFile.GetPlayer(FileComponent.PlayerInventory));
Since i am loading that string from file it is possible it is just blank and i want to first check if it is blank and i would do it like this:
if(GFile.GetPlayer(FileComponent.PlayerInventory) != " ")
{
inventory = JsonUtility.FromJson<InventoryModel>(GFile.GetPlayer(FileComponent.PlayerInventory));
}
So my question is if there is any more elegant way of doing this instead of typing if statement like this?
Why not like this? :
var player = GFile.GetPlayer(FileComponent.PlayerInventory);
if(!string.IsNullOrWhiteSpace(player)) {
inventory = JsonUtility.FromJson<InventoryModel>(player);
}
I'd suggest
string data = GFile.GetPlayer(FileComponent.PlayerInventory);
if(!string.IsNullOrWhiteSpace(data))
{
inventory = JsonUtility.FromJson<InventoryModel>(data);
}
This way you only call GetPlayer once, and it doesn't matter if the resulting data is an empty string or is full of whitespace - it still won't enter that block and set inventory.
Edit
For older versions of .Net, this will also work
string data = GFile.GetPlayer(FileComponent.PlayerInventory);
if(data != null && data.Trim().Length == 0)
{
inventory = JsonUtility.FromJson<InventoryModel>(data);
}

Display all values except the null reference object

I have a foreach loop that is pulling data from an XML file, however some fields are blank. When the loop tries to pull a specific value it will sometimes get a null reference exception. Is there a way to single out the variable that has the null value and set it to an empty string while displaying all the other values in an efficient way? For the sake of the example lets say the address field is returning the null value.
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(id);
XmlNodeList person = xmldoc.SelectNodes("//parent/child");
foreach (XmlNode node in person)
{
try
{
var name = node["name"].InnerText;
var phone = node["phone"].InnerText;
var email = node["email"].InnerText;
var address = node["address"].InnerText;
lblPopulate2.Text = name;
lblPopulate7.Text = address;
lblPopulate5.Text = phone;
lblPopulate6.Text = email;
}
catch(NullReferenceException ex)
{
???
}
finally
{
}
You could use the null conditional operator which would return null if the address node is not present, otherwise the InnerText.
var address = node["address"]?.InnerText;
And then the null coalescing operator for setting your Text property:
lblPopulate7.Text = address ?? string.Empty;

The best overloaded method match for... has some invalid arguments

I am using DataAdapter("SDM_Tran_GenerateInvoice") inside DataSet("SDMDAL.xsd") in my project.
Below is the structure of DataAdapter along with the Stored Procedure names in it:
Below is the Table structure Im using for the same:
I am calling this DataAdapter inside Class file named as SDM.InvoiceBLL.cs:
using SDMDALTableAdapters;
public class SDM_Invoice
{
private SDM_Tran_GenerateInvoiceTableAdapter _GenerateInvoiceTableAdapter = null;
protected SDM_Tran_GenerateInvoiceTableAdapter Adapter
{
get
{
if (_GenerateInvoiceTableAdapter == null)
_GenerateInvoiceTableAdapter = new SDM_Tran_GenerateInvoiceTableAdapter();
return _GenerateInvoiceTableAdapter;
}
}
#region GET
//to show data in Invoice Grid
public SDMDAL.SDM_Tran_GenerateInvoiceDataTable SelectInvoice(string _SPID)
{
return Adapter.SelectInvoice(_SPID);
}
//to show data in 1st hidden Grid
public SDMDAL.SDM_Tran_GenerateInvoiceDataTable GetInvoiceBillingBySPID(string _SPID)
{
return Adapter.GetInvoiceBillingBySPID(_SPID);
}
//to fetch InvoiceID for unique key generation
public SDMDAL.SDM_Tran_GenerateInvoiceDataTable GetInvoiceID()
{
return Adapter.GetInvoiceID();
}
//to fetch InvoiceNumber for unique key generation
public SDMDAL.SDM_Tran_GenerateInvoiceDataTable GetInvoiceNumber()
{
return Adapter.GetInvoiceNumber();
}
#endregion
public string Insert(string InvoiceID, string SPfoID, string InvoiceLineNo, string InvoiceNo, string InvoiceType, string BillingIDfoID, string BusinessUnit, string DirectCost, string InvfoStatusID, string Status, DateTime Date, string AccountCode)
{
string query = Convert.ToString(Adapter.Insert1(InvoiceNo, SPfoID, InvoiceLineNo, InvoiceNo, InvoiceType, BillingIDfoID, BusinessUnit, DirectCost, InvfoStatusID, Status, Date, AccountCode));
return query;
}
public SDM_Invoice()
{
}
}
and then calling the "Insert" function of class file inside Default.aspx.cs page, to save records on button click:
protected void btnInvoice_Click(object sender, EventArgs e)
{
generateInvoiceId();
generateInvoiceNumber();
string InvType = rlbInvType.SelectedValue;
string Status = "Draft";
string BillingID;
string DirectCost;
string BusinessUnit;
string StatusID;
string AccCode;
foreach (GridDataItem itm in rgData.Items)
{
BillingID = itm["BillingID"].Text;
DirectCost = itm["DCIDescription"].Text;
BusinessUnit = itm["BUName"].Text;
StatusID = itm["BUfoStatusID"].Text;
Label lb = (Label)itm.FindControl("Label1");
string InvLineNo = lb.Text;
try
{
SDM.Invoice.Insert(lblInvId.Text, _SPID, InvLineNo, lblInvNo, InvType, BillingID, BusinessUnit, DirectCost, StatusID, Status, DateTime.Now, AccCode);
}
catch (Exception ex)
{
}
}
}
I rebuilt my project number of times and when I run my web page "Default.aspx.cs", always it gives me below error:
The best overloaded method match for 'SDM_Invoice.Insert(string, string, string, string, string, string, string, string, string, string, System.DateTime, string)' has some invalid arguments
I searched many articles related to my issue but couldn't find any solution for my problem.
This is the first time I am working with TableAdapter. Please help me what is wrong in my code ? What am I missing in it. Thanks in advance.
All the arguments except for the next to last need to be strings, but you seem to be passing some non-string values, for example lblInvNo, which seems to be a user interface element.
Check the type of each argument aside from the next to last, and make sure they are all strings.

Checking for empty string before inserting the record

I am custom importing some rows from a text file to our database and so I have bunch of codes like this for many fields.
address.State = row["Location State"].ToString();
I just noticed a requirement that says
don't overwrite those fields in the value that we are reading from the
text file is empty or blank.
So I assume I can wrap them all around a check like this?
if(!String.IsNullOrEmpth(row["Location State"].ToString()))
address.State = row["Location State"].ToString();
But before I go ahead and apply this kind of logic around all those fields I wanted to check and see if you have better solutions?
Maybe an extension method could help here:
public static string ColumnValueOrDefault(this DataRow row, string column, string defaultValue)
{
if (row == null)
{
throw new ArgumentNullException("row");
}
if (column == null)
{
throw new ArgumentNullException("column");
}
if (defaultValue == null)
{
throw new ArgumentNullException("defaultValue");
}
var rowString = row[column].ToString();
return string.IsNullOrEmpty(rowString) ? defaultValue : rowString;
}
Address.State = row.ColumnValueOrDefault("column", Address.State);
I would (and do) use this pattern personally :
string sTester = string.Empty
Address.State = string.IsNullOrEmpty(sTester = row["collumn"].ToString()) == false ? sTester : Address.State;
This allows each collumn value to be set once, and the reused using the same string variable, and is relatively readable

Convert combobox string value to int

I have a question about converting types. I want to change the currently selected combobox value string to an int, but I get errors
My code:
int.Parse(age.SelectedItem.ToString());
What can I do for this problem?
Ok now we know the error, you can check for a null value before trying to parse it using:
if (comboBox1.SelectedItem != null)
{
int x = int.Parse(comboBox1.SelectedItem.ToString());
}
else { //Value is null }
You can avoid a null value being passed by setting the text property of the control to what ever default value you want.
If you are still not getting a value after making sure one is selected you really need to post your code.
TryParse is a good method for this sort of thing:
int value;
if (!Int32.TryParse(this.comboBoxNumeric.Text, out value))
{
//Do something fun...
}
Use a Convert.ToInt32 method. You can always use the databinding like this:
class A
{
public int ID{get;set;}
public string Name{get;set;}
}
cbo.DataSource = new A[]{new A{ID=1, Name="hello"}};
cbo.DisplayMember = "Name";
cbo.DisplayValue = "ID";
int id = Convert.ToInt32(cbo.SelectedValue);
A a = (A) cbo.SelectedItem;
int a_id = a.ID;
int a_name = a.Name;
If you use LINQ to DataSets, develop is very easy for C# program.
try
{
string name = comboBoxPort.SelectedItem.ToString();
int portBaudrate = Convert.ToInt32(comboBoxBaudrate.SelectedItem);
}
//just solved
//enjoy

Categories

Resources