comboBox replace null to empty string - c#

What can I do to detect when in comboBox I have null because user choose nothing, and replace it for empty string? I use for fill comboBox DataSource.
if (comboBoxTransport.SelectedItem.ToString() == null)
comboBoxMaintenance.SelectedItem = "";
this.dataGridViewOffer.DataSource = soc.FindOffer(comboBoxCountry.SelectedItem.ToString(), comboBoxAccommodation.SelectedItem.ToString(),
comboBoxTransport.SelectedItem.ToString(), comboBoxMaintenance.SelectedItem.ToString()).ToList();
I need it to correctly call method:
public List<Oferty1> FindOffer(string country, string accommodation, string transport, string maintenance) {...}
Or in how other way can I convert null to string in this case?

You can use Ternary Operator to check it wherever you need:
comboBoxTransport.SelectedItem == null ? String.Empty : comboBoxTransport.SelectedItem.ToString()
Complete Code:
if (comboBoxTransport.SelectedItem == null) //ToString can not be called if property is null
comboBoxMaintenance.SelectedItem = "";
this.dataGridViewOffer.DataSource =
soc.FindOffer(
comboBoxCountry.SelectedItem == null ? String.Empty : comboBoxCountry.SelectedItem.ToString(),
comboBoxAccommodation.SelectedItem == null ? String.Empty : comboBoxAccommodation.SelectedItem.ToString(),
comboBoxTransport.SelectedItem == null ? String.Empty : comboBoxTransport.SelectedItem.ToString(),
comboBoxMaintenance.SelectedItem == null ? String.Empty : comboBoxMaintenance.SelectedItem.ToString()
).ToList();

Related

System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression. in c#

I am getting error on insert and update while i am providing number data in TXT_Firm_Pincode.Text and TXT_Firm_Bank_Ac_No.Text and when i am leaving this both fields empaty its working perfect can anybody help me out.
MC.Cmd_SQL = new OleDbCommand($#"Update TBL_Firm set
Firm_Owner = '{TXT_Firm_Owner.Text}',
Firm_Name = '{TXT_Firm_Name.Text}',
Firm_Address = '{TXT_Firm_Address.Text}',
Firm_City = '{TXT_Firm_City.Text}',
Firm_Pincode = #Firm_Pincode,
Firm_State= '{CB_Firm_State.Text}',
Firm_Con_Person = '{TXT_Firm_Con_Person.Text}',
Firm_Con_No = {TXT_Firm_Con_No.Text},
Firm_GSTN = '{TXT_Firm_GSTN.Text}',
Firm_Bank_Name = '{TXT_Firm_Bank_Name.Text}',
Firm_Bank_Ac_No = #Firm_Bank_Ac_No,
Firm_Bank_Branch = '{TXT_Firm_Bank_Branch.Text}',
Firm_Bank_IFSC= '{TXT_Firm_Bank_IFSC.Text}',
Firm_MailID = '{TXT_Firm_MailID.Text}'
where Firm_ID = {TXT_Firm_ID.Text}", MC.DB_Connection);
MC.Cmd_SQL.CommandType = CommandType.Text;
MC.Cmd_SQL.Parameters.AddWithValue("#Firm_Pincode" , TXT_Firm_Pincode.Text == "" ? DBNull.Value : (object)"Null");
MC.Cmd_SQL.Parameters.AddWithValue("#Firm_Bank_Ac_No", TXT_Firm_Bank_Ac_No.Text == "" ? DBNull.Value : (object)"Null");
MC.Cmd_SQL.ExecuteNonQuery();
Ternary operator condition ? operand1 : operand2 returns operand1 when condition is true and false - otherwise.
It is all right with your operand1 statement, but you need to change operand2 to put text box value in it:
MC.Cmd_SQL.Parameters.AddWithValue("#Firm_Pincode" ,
TXT_Firm_Pincode.Text == "" ? DBNull.Value : TXT_Firm_Pincode.Text);
MC.Cmd_SQL.Parameters.AddWithValue("#Firm_Bank_Ac_No",
TXT_Firm_Bank_Ac_No.Text == "" ? DBNull.Value : TXT_Firm_Bank_Ac_No.Text);

IDataReader runtime error

I'm trying to populate my Request using the IDataReader but for some of the properties the values are coming back as null from the database, this then throws an exception because it doesn't like the null.
public static void Populate(IDataReader datareader, Request request)
{
request._requestID = datareader.IsDBNull(datareader.GetOrdinal("RequestID")) ? null : (int?)datareader.GetInt32(datareader.GetOrdinal("RequestID"));
request._appversion = datareader.GetString(datareader.GetOrdinal("AppVersion"));
request._apprequestguid = datareader.IsDBNull(datareader.GetOrdinal("AppRequestGUID")) ? null : datareader.GetString(datareader.GetOrdinal("AppRequestGUID"));
request._sourceip = datareader.IsDBNull(datareader.GetOrdinal("SourceIP")) ? null : datareader.GetString(datareader.GetOrdinal("SourceIP"));
request._cli = datareader.IsDBNull(datareader.GetOrdinal("CLI")) ? null : datareader.GetString(datareader.GetOrdinal("CLI"));
request._handsetid = datareader.IsDBNull(datareader.GetOrdinal("HandsetID")) ? null : datareader.GetString(datareader.GetOrdinal("HandsetID"));
request._service = datareader.IsDBNull(datareader.GetOrdinal("Service")) ? null : datareader.GetString(datareader.GetOrdinal("Service"));
request._requestrespcode = datareader.IsDBNull(datareader.GetOrdinal("RequestRespCode")) ? null : datareader.GetString(datareader.GetOrdinal("RequestRespCode"));
request._fraudmatchid = datareader.IsDBNull(datareader.GetOrdinal("FraudMatchID")) ? null : (int?)datareader.GetInt32(datareader.GetOrdinal("FraudMatchID"));
request._action = datareader.IsDBNull(datareader.GetOrdinal("Action")) ? null : datareader.GetString(datareader.GetOrdinal("Action"));
request._detail = datareader.IsDBNull(datareader.GetOrdinal("Detail")) ? null : datareader.GetString(datareader.GetOrdinal("Detail"));
request._apprespcode = datareader.IsDBNull(datareader.GetOrdinal("AppRespCode")) ? null : datareader.GetString(datareader.GetOrdinal("AppRespCode"));
request._createddttm = datareader.IsDBNull(datareader.GetOrdinal("CreatedDttm")) ? null : (DateTime?)datareader.GetDateTime(datareader.GetOrdinal("CreatedDttm"));
request._modifieddttm = datareader.IsDBNull(datareader.GetOrdinal("ModifiedDttm")) ? null : (DateTime?)datareader.GetDateTime(datareader.GetOrdinal("ModifiedDttm"));
}
I have tried adding but when I debug it doesn't reach the if statement.
if (request._appversion.Equals(null))
{
request._appversion = string.Empty;
}
What code can I add code so that it doesn't break if it gets a null from the database?
You can try this approach:
request._detail = Convert.ToString(datareader.Item("Detail"));
It should work because Convert.ToString(Convert.DBNull) = String.Empty.
Reference:
SqlDataReader.Item

Linq to XML to create 1 record per specific element

Here is an XML Element "inspection" with child Elements "driver", "vehicle" and "violation", for which I need the Attribute values.
I need to create one record for each inspection that also contains the other element's attribute values.
<inspection inspection_date="2012-07-08" report_state="IL" report_number="ILP4E1014879" level="1" time_weight="1">
<driver first_name="MELVIN" last_name="DANIELS" date_of_birth="1976-12-20" license_state="IL" License_number="D8505003"></driver>
<vehicle vehicle_id_number="1HSCNAPR74C501842" unit_type="Truck Tractor" license_state="IL" license_number="1234567"></vehicle>
<violations>
<violation code="122.4B2C" description="Lights" oos="N" basic="Vehicle Maint." severity_weight="4"></violation>
</violations>
</inspection>
Here is a snippet:
dotinspections = from el in inspectionList
select el;
foreach (var el in dotinspections)
{
if (el.Attribute("inspection_date") != null && el.Attribute("inspection_date").Value != null)
{ insDate = Convert.ToDateTime(el.Attribute("inspection_date").Value); }
state = el.Attribute("report_state") != null && (string)el.Attribute("report_state").Value != null ? el.Attribute("report_state").Value.Replace("'", "''") : null;
insNumber = el.Attribute("report_number") != null && el.Attribute("report_number").Value != null ? el.Attribute("report_number").Value.Replace("'", "''") : null;
if (el.Attribute("level") != null && el.Attribute("level").Value != null)
{ insLevel = Convert.ToInt32(el.Attribute("level").Value); }
These are in an IEnumerable "dotinspections". I have tried just about every method using .Elements, .Descendants, .Attributes etc.., but can only get an inspection record, then a driver record, then vehicle, etc.., not one record for each full inspection.
How can I get one record per inspection?
Lesson learned - thanks webdad3.
I didn't post all my code (for brevity). The problem was me not going deeper into the nested XElements. I needed to add "violations" and "vehicle" and other ancestors to my attributes:
licenseNumber1 = el.Element("vehicle").Attribute("license_number") != null && el.Element("vehicle").Attribute("license_number").Value != null ? el.Element("vehicle").Attribute("license_number").Value.Replace("'", "''") : null;
code = el.Element("violations").Element("violation").Attribute("code") != null && el.Element("violations").Element("violation").Attribute("code").Value != null ? el.Element("violations").Element("violation").Attribute("code").Value.Replace("'", "''") : null;
description = el.Element("violations").Element("violation").Attribute("description") != null && el.Element("violations").Element("violation").Attribute("description").Value != null ? el.Element("violations").Element("violation").Attribute("description").Value.Replace("'", "''") : null;

Don't have a nullReferenceException on XML Parsing

I have wrote a c# function in order to parse an XML Stream.
My XML can have several nodes.
Example :
<Stream>
<One>nnn</One>
<Two>iii</Two>
<Three>jjj</Three>
</Stream>
But sometimes, it is :
<Stream>
<Two>iii</Two>
</Stream>
Here is my c# code :
var XML = from item in XElement.Parse(strXMLStream).Descendants("Stream") select item;
string strOne = string.Empty;
string strTwo = string.Empty;
string strThree = string.Empty;
if ((item.Element("One").Value != "")
{
strOne = item.Element("One").Value;
}
if ((item.Element("Two").Value != "")
{
strTwo = item.Element("Two").Value;
}
if ((item.Element("Three").Value != "")
{
strThree = item.Element("Three").Value;
}
With this code, if my Stream is full ( Node On, Two and three), there's no problem! But, if my Stream has only the node "Two", I get a NullReferenceException.
Is there a way to avoid this exception (I cannot change my Stream).
Thanks a lot :)
You should check if item.Element("anything") is null before accessing it's Value property.
if (item.Element("Three") != null && item.Element("Three").Value != "")
You need to do:
if (item.Element("One") != null)
{
strOne = item.Element("One").Value;
}
.Element(String) returns null if an element of the name you requested does not exist.
Checking if value != "" is pointless, because all you are preventing is the reassignment of an empty string to the strOne variable, which is already an empty string. Also, if you really needed to do the empty string check, using String.IsNullOrEmpty(String) method is the preferred way.
Instead of accessing Value property (which raises NullReferenceException if element not exist, as you already know) cast elements to strings. You can use ?? to provide default value for non-existing elements:
string strOne = (string)item.Element("One") ?? String.Empty;
string strTwo = (string)item.Element("Two") ?? String.Empty;
string strThree = (string)item.Element("Three") ?? String.Empty;

how to set database string value to null?

There are some value contain in my database branch column for example "B01",
I am trying to set my branch column back to null value
I had tried
string.Empty
String.Empty
""
null
DBNull.value
Noted* all the method able to set my value back to "" but not my expected result, my expected result is my column back to "NULL" but not ""
if (ddlBranches.SelectedIndex > 0 && ddlLocation.SelectedItem.Text.ToUpper() == "BRANCH")
{
drUpdProb["Branch"] = ddlBranches.SelectedValue.ToString();
drUpdProb["BranchAbbr"] = ddlBranches.SelectedItem.Text;
}
else
{
drUpdProb["Branch"] = DBNull.value;
drUpdProb["BranchAbbr"] = DBNull.value;
}
Try something like the following create a parameter to assign values
cmd.Parameters.AddWithValue("#Branch", drUpdProb["Branch"] ?? (object)DBNull.Value);
cmd.Parameters.AddWithValue("#BranchAbbr", drUpdProb["BranchAbbr"] ?? (object)DBNull.Value);

Categories

Resources