I want to increment a number in a string.
My model:
public partial class updown
{
public int id { get; set; }
public string number { get; set; }
}
My controller:
[HttpPost]
public ActionResult Index(updown viewModel)
{
var lastPO = db.updowns
.OrderByDescending(o => o.number)
.Select(m => m.number)
.FirstOrDefault() ?? "00001";
item.number = lastPO++; // I get an error on this line
db.updowns.Add(item);
db.SaveChanges();
return View(viewModel);
}
The error:
Operator '++' cannot be applied to operand of type 'string'
Expected result:
item.number // "00002"
Based on the now-deleted comments, I have:
[HttpPost]
public ActionResult Index(updown viewModel)
{
var s = db.updowns
.OrderByDescending(o => o.number)
.Select(m => m.number)
.FirstOrDefault() ?? "00001/S2";
var lastPO = Convert.ToInt32(s.Substring(s.Length - 5 - 3, s.Length - 3)); // *
item.number = "EMOC-" + (++lastPO).ToString("00000");
db.updowns.Add(item);
db.SaveChanges();
return View(viewModel);
}
Expected result:
item.number // "EMOC-00002/S2"
But I get an error on the line marked // *
when I run it the second time.
I tried doing a little bit of your code. It seems fine
i think the problem lies in here
var s = db.updowns
.OrderByDescending(o => o.number)
.Select(m => m.number)
.FirstOrDefault() ?? "00001/S2";
the ?? "00001/S2"
?? "00001/S2"
might be triggering the error. try doing a break point in var s
... and see if all of s.number has value or has a correct convertible value (there could be just letters which can't be converted)
Expected result:
item.number // "EMOC-00002/S2"
You need + "/S2"
here:
item.number = "EMOC-" + (++lastPO).ToString("00000") + "/S2";
What happens when you ran previous code the second time is that var s = "EMOC-00002"
so s.Substring(s.Length - 5 - 3, s.Length - 3)
gives "OC-00"
instead of "00002"
string, which Convert.ToInt32()
cannot handle.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.