This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is a NullReferenceException in .NET?
I am a beginner in MVC and I have tried to add a dropdown list to save its selected value in database using sql queries but my code throws a NullReferenceException.
Can anyone help me please?
This is the model
public class caradvert
{
[Required]
public SelectList GearType { get; set; }
public int Selected { get; set; }
public caradvert()
{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem()
{
Value = "0",
Text = "اتوماتيك "
});
listItems.Add(new SelectListItem()
{
Value = "1",
Text = "عادي"
});
GearType = new SelectList(listItems, "Value", "Text");
}
public int CreatAdvert(int userid)
{
SqlConnection objConn = new SqlConnection("Data Source=ADMIN-PC;Initial Catalog=mvc4advertisment;Integrated Security=True");
SqlCommand objCmd = new SqlCommand();
objCmd.CommandType = CommandType.Text;
objCmd.CommandText = "insert into Mercedes(Model,GearType,color,EngineCapacity,CarDescription,Price,Image1Url,Image2Url,Image3Url,Userid,State) values('1','" + GearType.SelectedValue.ToString() + "','r','221','ddd','2','ss','ss','ss','1','False')";
objCmd.Connection = objConn;
objConn.Open();
int count = (int)objCmd.ExecuteNonQuery();
objConn.Close();
return count;
}
}
This is controller
[HttpGet]
public ActionResult CreateAdvert()
{
caradvert model = new caradvert();
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem()
{
Value = "1",
Text = "اتوماتيك "
});
listItems.Add(new SelectListItem()
{
Value = "1",
Text = "عادي"
});
model.GearType = new SelectList(listItems, "Value", "Text");
return View(model);
}
[HttpPost]
public ActionResult CreateAdvert(caradvert model )
{
int _records = model.CreatAdvert(1);
if (_records > 0)
{
return RedirectToAction("Index", "Account");
}
else
{
ModelState.AddModelError("", "لا يمكنك اضافة اعلان");
}
return View(model);
}
This is the view
<%:Html.DropDownListFor(m=>m.Selected,Model.GearType,") %>
Most likely the GearType or GearType.SelectedValue are null in this statement.
objCmd.CommandText = "insert into Mercedes(Model,GearType,color,EngineCapacity,CarDescription,Price,Image1Url,Image2Url,Image3Url,Userid,State) values('1','" + GearType.SelectedValue.ToString() + "','r','221','ddd','2','ss','ss','ss','1','False')";
at this line:
objCmd.CommandText = "insert into Mercedes(Model,GearType,color,EngineCapacity,CarDescription,Price,Image1Url,Image2Url,Image3Url,Userid,State) values('1','" + GearType.SelectedValue.ToString() + "','r','221','ddd','2','ss','ss','ss','1','False')";
If GearType is not initialized or null
If GearType.SelectedValue is null
GearType.SelectedValue.ToString() can throw an exception like reference not set to an instance of an object.
To make problem more clear you can control GearType and GearType.SelectedValue before this line.
if(GearType != null && GearType.SelectedValue != null) {
Mercedes(Model,GearType,color,EngineCapacity,CarDescription,Price,Image1Url,Image2Url,Image3Url,Userid,State) values('1','" + GearType.SelectedValue.ToString() + "','r','221','ddd','2','ss','ss','ss','1','False')";
}
Related
I have a SQL-server and a column called CitizenshipDate. That column is of type datetime in the SQL.
However, the problem is that it can have the value '0' which is NOT a datetime value but rather a string value.
So what I'm trying to do is to handle it as a string in C# when inserting it values but get the error:
Conversion failed when converting datetime from character string.
I get that error because I'm trying to insert string into a datetime in the SQL-server.
Here is my code:
class Person {
public string PersonalIdentityNumber { get; set; }
public string SpecialIdentityNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string CitizenshipDate { get; set; }
}
List<FolkbokforingspostTYPE> deserializedList = new List<FolkbokforingspostTYPE>();
deserializedList = Deserialize<List<FolkbokforingspostTYPE>>();
var myPersons = Deserialize<List<FolkbokforingspostTYPE>>()
.Select(x => new Person
{
PersonalIdentityNumber = x.Personpost.PersonId.PersonNr,
SpecialIdentityNumber = x.Personpost.PersonId.Tilltalsnamnsmarkering != null ? x.Personpost.PersonId.Tilltalsnamnsmarkering : null,
LastName = x.Personpost.Namn.Efternamn,
FirstName = x.Personpost.Namn.Fornamn,
CitizenshipDate = x.Personpost.Medborgarskap != null ? x.Personpost.Medborgarskap.Medborgarskapsdatum : null
});
string connetionString = null;
SqlDataAdapter adpter = new SqlDataAdapter();
DataSet ds = new DataSet();
XmlReader xmlFile;
connetionString = "Data Source=tsrv2062;Initial Catalog=Bums;User ID=BumsUser;Password=2tusen7Bums";
xmlFile = XmlReader.Create("navetout.xml", new XmlReaderSettings());
ds.ReadXml(xmlFile);
using (var connection = new SqlConnection(connetionString))
{
connection.Open();
DateTime datum = DateTime.Now;
string LastChangedBy = "System";
foreach (Person p in myPersons)
{
SqlCommand command1 = Avreg(p.UnregistrationReason, p.GivenNameNumber,p.ProtectedIdentity, p.CitizenshipDate, connection);
command1.Parameters.AddWithValue("#PersonalIdentityNumber", string.Format("{0}{1}", p.PersonalIdentityNumber, p.SpecialIdentityNumber));
command1.Parameters.AddWithValue("#FirstName", p.FirstName);
command1.Parameters.AddWithValue("#LastName", p.LastName);
command1.ExecuteNonQuery();
Console.WriteLine(string.Format("{0}{1}", p.PersonalIdentityNumber, p.SpecialIdentityNumber));
}
}
Console.WriteLine("Done");
// }// Put a break-point here, then mouse-over PersonalIdentityNumber... deserializedList contains everything if you need it
//catch (Exception)
// {
// throw;
// }
Console.ReadKey();
}
public static SqlCommand Avreg(string s, string t, string p, string c, SqlConnection connection)
{
var query = "UPDATE Seamen SET FirstName = #FirstName, "+
"LastName = #LastName, "+
SqlCommand command1;
//Here is the `CitizenshipDate`
if (c == "0")
{
query += ", CitizenshipDate = '0'";
command1 = new SqlCommand(query, connection);
command1.Parameters.Clear();
}
else
{
query += ", CitizenshipDate = #CitizenshipDate";
command1 = new SqlCommand(query, connection);
command1.Parameters.Clear();
command1.Parameters.AddWithValue("#CitizenshipDate", c ?? DBNull.Value.ToString());
}
//Ignore these if statements
if ((!string.IsNullOrEmpty(s)) && !string.IsNullOrEmpty(t))
{
}
else
{
query += ", GivenNameNumber = #GivenNameNumber WHERE PersonalIdentityNumber = #PersonalIdentityNumber";
t = "00";
command1 = new SqlCommand(query, connection);
command1.Parameters.Clear();
command1.Parameters.AddWithValue("#GivenNameNumber", t ?? DBNull.Value.ToString());
return command1;
}
return command1;
}
Please note that I cannot change the type in the database. I somehow need a way to insert the value from String.
Can someone help ?
If the column does not allow nulls, then you can use NULL to represent "0", and then in code, when loading the record, replace NULL with "0" in the UI. Or, if you do allow NULLS and need another value to represent "0", you can use an arbitrary date you wouldn't normally use like '1/1/1753' (the lowest value for SQL datetime) or '1/1/1900' (lowest for smalldatetime) or something like that. Any date that is these dates represents "0". So the conversion to "0" happens within the app, not stored in the database.
If your column supports null you can fix it like this:
if (c == "0")
{
query += ", CitizenshipDate = NULL--instead of '0'";
If it does not support NULL values you will have to insert a default value such as DateTime.MinValue.
I want to make a library system in C#. In this system when a book is issued it should automatically reduce the book quantity in database. When book quantity == 0 there should be a message box showing "not available".
This is my code:
private void btnIssue_Click(object sender, EventArgs e)
{
if (cmbResID.Text != "" && cmbMemID.Text != "" && cmbBookID.Text != "" && txtBkTitle.Text != "" && txtCategory.Text != "" && txtAuthor.Text != "" && txtIssueDate.Text != "" && txtActDate.Text != "")
{
SqlCommand Quantity = new SqlCommand("Select * from tblBookDetails where Book_ID = '" + cmbBookID.Text +"'");
DataSet ds = Library.Select(Quantity);
if (ds.Tables[0].Rows.Count > 0)
{
textBox1.Text = ds.Tables[0].Rows[0].ItemArray.GetValue(5).ToString();
int b = Convert.ToInt32(textBox1.Text);
if (b > 0)
{
//a = a - 1;
//int b = Convert.ToInt32(a);
//label15.Text = a.ToString();
SqlCommand update=new SqlCommand("UPDATE tblBookDetails SET Quantity=Quantity-1 WHERE Book_ID='"+ cmbBookID +"'");
Library.ExecuteInsert(update);
SqlCommand save = new SqlCommand("insert into tblBookIssue values(#ResID,#Member_ID,#Book_ID,#Issue_Date,#Act_Ret_Date)");
save.Parameters.AddWithValue("#ResID", cmbResID.Text);
save.Parameters.AddWithValue("#Member_ID", cmbMemID.Text);
save.Parameters.AddWithValue("#Book_ID", cmbBookID.Text);
save.Parameters.AddWithValue("#Issue_Date", txtIssueDate.Text);
save.Parameters.AddWithValue("#Act_Ret_Date", txtActDate.Text);
Library.Insert(save);
MessageBox.Show("Book Issued", "Book Issue", MessageBoxButtons.OK, MessageBoxIcon.Information);
clear();
}
else
{
MessageBox.Show("this book is not available");
}
}
}
else
{
MessageBox.Show("FILL COLUMS");
}
}
Executing SQL based off of text boxes is very unsafe and Prone to SQL injection attacks. Also, to follow Object Oriented program and make much cleaner code it would be advisable to make a Book object, I completed some code below which shows an example including the book incrementer. It would be better to make focused stored procs which execute gets for books and updates for book checkouts. You will have to turn your basic select into a stored proc, and write another proc which looks at the quantity and if quantity < 1 return 0 else return 1. Let me know if you need more info, this code should help you get rolling
using System;
using System.Data;
using System.Data.SqlClient;
namespace MockLibrary
{
internal class Book
{
#region Constructors
public Book()
{
}
public Book(string resId, string memberId, string bookId, DateTime issueDate, DateTime actRetDate)
{
this.ResId = resId;
this.MemberId = memberId;
this.BookId = bookId;
this.IssueDate = issueDate;
this.ActRetDate = actRetDate;
}
#endregion
#region Properties
private string _ResID;
private string _MemberID;
private string _BookId;
private DateTime _IssueDate;
private DateTime _ActRetDate;
public string ResId
{
get { return _ResID; }
set { _ResID = value; }
}
public string MemberId
{
get { return _MemberID; }
set { _MemberID = value; }
}
public string BookId
{
get { return _BookId; }
set { _BookId = value; }
}
public DateTime IssueDate
{
get { return _IssueDate; }
set { _IssueDate = value; }
}
public DateTime ActRetDate
{
get { return _ActRetDate; }
set { _ActRetDate = value; }
}
#endregion
public Book GetBookByID(string resId, string memberId)
{
try
{
using (SqlConnection con = new SqlConnection("put your db con string here"))
{
using (SqlCommand cmd = new SqlCommand("sp_GetBookById", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ResId", SqlDbType.VarChar).Value = resId;
cmd.Parameters.Add("#MemberId", SqlDbType.VarChar).Value = memberId;
con.Open();
cmd.ExecuteNonQuery();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Book newBook = new Book(rdr["ResId"].ToString(),rdr["MemberId"].ToString(),rdr["BookId"].ToString(),DateTime.Now,DateTime.Now);
return newBook;
}
}
}
}
catch
{
throw new Exception("something went wrong");
}
return null;
}
public bool CheckoutBook(string resId, string memberId)
{
using (SqlConnection con = new SqlConnection("put your db con string here"))
{
using (SqlCommand cmd = new SqlCommand("sp_CheckoutBook", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ResId", SqlDbType.VarChar).Value = resId;
cmd.Parameters.Add("#MemberId", SqlDbType.VarChar).Value = memberId;
con.Open();
cmd.ExecuteNonQuery();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (rdr["checkoutsuccessful"].ToString() == "1")
{
return true;
}
}
}
}
return false;
}
}
}
when user returns a book:-
MySqlCommand cm1;
cm1 = new MySqlCommand("update addbook set bookquantity=bookquantity+1 where bookname='" + txt_bookname.Text + "'",con);
cm1.ExecuteNonQuery();
Here I have two dropdownlists. First one to display the list of countries and the second to list the states value for selected country from first. The list of values are populated from
properly but in the dropdownlist, the values are not populated.
jQuery:
$(document).ready(function () {
$("#Country").change(function () {
var Id = $('#Country option:selected').attr('value');
$("#Region").empty();
$.getJSON("/ControllerName/GetRegionList",{ ID: Id },
function (data) {
jQuery.each(data, function (key) {
$("#Region").append($("<option></option>").val(ID).html(Name));
});
});
});
});
View :
#Html.DropDownList("Country", new SelectList(Model.CountryList, "Value", "Text", Model.CountryList.SelectedValue))
#Html.DropDownList("Region", new SelectList(Model.RegionList, "Value", "Text", Model.RegionList.SelectedValue))
Controller:
public List<Region> GetRegionList(int ID)
{
int countryid = ID;
AddressModel objmodel = new AddressModel();
List<Region> objRegionList = new List<Region>();
objRegionList.Add(new Region { ID = "0", Name = " " });
if (countryid != 0)
{
countryid = Convert.ToInt32(ID);
SqlCommand cmd = new SqlCommand("USP_ProcedureName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Id", countryid);
cmd.Parameters.AddWithValue("#Mode", "Region");
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr["RegionId"].ToString() != "")
{
objRegionList.Add(new Region { ID = dr["RegionId"].ToString(), Name = dr["Name"].ToString() });
}
}
dr.Close();
con.Close();
}
return objRegionList;
}
What is the mistake in my code.? Any Suggestions.
EDIT : Added the snapshot
In ASP.NET MVC controller actions must return ActionResults. In your case you could return JSON:
public ActionResult GetRegionList(int id)
{
var objRegionList = new List<Region>();
objRegionList.Add(new Region { ID = "0", Name = " " });
if (countryid != 0)
{
int countryid = ID;
using (var conn = new SqlConnection("YOUR CONNECTION STRING COMES HERE"))
using (var cmd = conn.CreateCommand())
{
con.Open();
cmd.CommandText = "USP_ProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Id", countryid);
cmd.Parameters.AddWithValue("#Mode", "Region");
using (var dr = cmd.ExecuteReader())
{
while (dr.Read())
{
if (dr["RegionId"].ToString() != "")
{
objRegionList.Add(new Region
{
ID = dr["RegionId"].ToString(),
Name = dr["Name"].ToString()
});
}
}
}
}
}
return Json(objRegionList, JsonRequestBehavior.AllowGet);
}
Notice that I have also cleared your code from unused variables and unnecessary Convert.ToInt32 calls and most importantly wrapped IDisaposable resources such as SQL connections, commands and data readers in using statements to avoid leaking resources.
Then include the url of the controller action as a data-* attribute on the first dropdown to avoid ugly hardcoding it in your javascript and breaking when you deploy your application in IIS in a virtual directory:
#Html.DropDownList(
"Country",
new SelectList(Model.CountryList, "Value", "Text", Model.CountryList.SelectedValue),
new { data_url = Url.Action("GetRegionList", "ControllerName") }
)
finally adapt (simplify) your javascript:
$('#Country').change(function () {
var regionDdl = $('#Region');
regionDdl.empty();
var id = $(this).val();
var url = $(this).data(url);
$.getJSON(url, { id: id }, function (data) {
$.each(data, function (index, region) {
regionDdl.append(
$('<option/>', {
value: region.ID,
html: region.Name
})
);
});
});
});
I am trying to retrieve all Names, from the Names tables in the database. I am unable to retrieve the data and return it as a lIst. how can i do it ?
public List<SelectListItem> getNames()
{
try
{
using (SqlCommand com = new SqlCommand("SELECT * FROM Names", con))
{
con();
SqlDataReader dr = com.ExecuteReader();
return ?? // How to return the items that was returned
}
}
.......
You can iterate over all rows returned as follows:
var items = new List<SelectListItem>();
while (dr.Read())
{
var valueInColumn1 = dr[1];
var valueInNamedColumn = dr["ColumnName"];
...
items.Add(new SelectListItem { Text = valueInColumn1.ToString(), Value = valueInNamedColumn.ToString());
}
return items;
First instantiate the list to hold your items (you could also leave it null but that depends on what your callers expect) and then iterate over the datareader by calling Read() until it returns false, which means no more records are available.
When the datareader has records you can fetch a column by calling one of the methods GetString, GetInt, GetLong etc supplying it the column you want to fetch as a parameter.
Construct the type you want to store in your list and add the retrieved values to its properties, add the new type to the List.
public List<SelectListItem> getNames()
{
var list = new List<SelectListItem>();
try
{
using (SqlCommand com = new SqlCommand("SELECT * FROM Names", con))
{
con();
SqlDataReader dr = com.ExecuteReader();
while (dr.Read())
{
list.Add(new SelectListItem {
Value = dr.GetString(0), // first column, depends on your table
Text = dr.GetString(1) // second column, depends on your table
});
}
catch(Exception e)
{
Trace.WriteLine(r.Message);
}
return list;
}
See my code example:
public static List<ActionItem> GetAllActions()
{
var actionItems = new List<ActionItem>();
SqlDataReader actionsReader = CatalogDB.GetAllActions();
try
{
while (actionsReader.Read())
{
actionItems.Add(new ActionItem
{
Id = (int)actionsReader["Id"],
Name = actionsReader["Name"] != DBNull.Value ? (string)actionsReader["Name"] : null,
Description = (string)actionsReader["Description"],
CreationDate = (DateTime)actionsReader["CreationDate"]
}
);
}
}
finally
{
actionsReader.Close();
}
return actionItems;
}
There are a couple of different ways, but this is probably the most straight forward.
public List<SelectListItem> getNames()
{
var list = new List<SelectedListItem>();
try
{
using (SqlCommand com = new SqlCommand("SELECT * FROM Names", con))
{
con();
SqlDataReader dr = com.ExecuteReader();
while (dr.Read())
{
var item = new SelectedListItem();
item.Value = dr[0];
list.Add(item);
}
}
}
catch(Exception ex)
{
// ...
}
return list;
}
So I've been working on learning LINQ, and I think I'm doing this correctly, but when I spit out the value of the DropDownList's DataValueField property, it comes back as the string "mId" rather than the actual value (the menu_id). Even more strange, the DataTextField is being populated correctly, using the same syntax. Anyone have any ideas?
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
List<RobDAL.Menu.menuObj> menuInfo = new List<RobDAL.Menu.menuObj>();
menuInfo = RobDAL.Menu.GetMenuText();
menu.DataSource = from myMenu in menuInfo
select new { Text = myMenu.menuText,
mId = myMenu.menuId };
menu.DataValueField = "mId";
menu.DataTextField = "Text";
menu.DataBind();
}
Here's my Menu class:
public class Menu
{
public static int GetMainMenuByContentId(int contentid)
{
//SqlConnection connection = new SqlConnection(Configuration.ConnectionInfo);
Content myContent = new Content();
int menuid;
string queryString = "SELECT menu_id FROM menu_to_item_tbl where content_id = " + contentid + ";";
using (SqlConnection connection = new SqlConnection(Configuration.ConnectionInfo))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
try
{
menuid = (int)command.ExecuteScalar();
}
finally
{
// Always call Close when done reading.
connection.Close();
}
return menuid;
}
}
public static List<menuObj> GetMenuText()
{
//SqlConnection connection = new SqlConnection(Configuration.ConnectionInfo);
List<menuObj> allMenus = new List<menuObj>();
string queryString = "SELECT DISTINCT menu_id, menu_title FROM menu_to_item_tbl;";
using (SqlConnection connection = new SqlConnection(Configuration.ConnectionInfo))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
menuObj myMenu = new menuObj();
myMenu.menuId = Convert.ToInt16(reader[0]);
myMenu.menuText = reader[1].ToString();
allMenus.Add(myMenu);
}
}
finally
{
reader.Close();
}
return allMenus;
}
}
public class menuObj
{
public string menuText { get; set; }
public int menuId { get; set; }
}
}
Thanks!
Change
menu.DataSource = from myMenu in menuInfo
select new { Text = myMenu.menuText,
mId = myMenu.menuId };
to
menu.DataSource = (from myMenu in menuInfo
select new { Text = myMenu.menuText,
mId = myMenu.menuId }).ToList();;
That is because you have assigned a string to the DataValue property of your drop down list.
menu.DataValueField = "mId".
You might also want to check to see what your linq query is returning for mId.