I am new to MVC.I am using a class library as Model and it reads data from the database and stores it in a Collection. Here is the code from the class library which reads records from sql database:
public IList<SemesterDetails> Read(User user )
{
string code; string name; int credits;int selfStudy;int modHrsPerWeek;
List<SemesterDetails> q = new List<SemesterDetails>();
using (SqlConnection db = new SqlConnection(AppConnect.Connection))
{
string query = "SELECT moduleCode,moduleName,modCredits,modHrsPerWeek,modHrsLeft FROM [Module] WHERE userName=#userName";
try
{
using (SqlCommand command=new SqlCommand(query,db))
{
if (db.State == ConnectionState.Closed)
{
db.Open();
command.Parameters.AddWithValue("#userName",user.UserName);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
code = reader.GetString(0);
name = reader.GetString(1);
credits = reader.GetInt32(2);
modHrsPerWeek = reader.GetInt32(3);
selfStudy = reader.GetInt32(4);
SemesterDetails semester = new SemesterDetails(code, name, credits,selfStudy);
q.Add(semester);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return q;
}
This gets called this action of the controller shown below:
public ActionResult EditStudyHrs(User user)
{
List <SemesterDetails >list= dataHandle.Read(user).ToList();
List<string> str = new List<string>();
foreach (var item in list)
{
str.Add(item.ModuleCode);
}
ViewBag.Modules = new SelectList(str, "ModuleCode", "ModuleCode");
return View();
}
I would like to bind Module code property to a Dropdownlist in this view:
<div class="form-horizontal">
<h4>Details</h4>
<hr />
#Html.DropDownList("Modules","SelctModuleCode")
</div>
SemesterDetails class:
public class SemesterDetails : ModuleInfo
{
private int numOfSemWeeks;
public int NumOfSemWeeks
{
get { return numOfSemWeeks; }
set { numOfSemWeeks = value; }
}
private DateTime startdate;
public DateTime StartDate
{
get { return startdate; }
set { startdate = value; }
}
private int studyHrsPerweek;
public int StudyHrsPerweek
{
get { return studyHrsPerweek; }
set { studyHrsPerweek = value; }
}
private DateTime endDate;
public DateTime EndDate
{
get { return endDate; }
set { endDate = value; }
}
private int selfStudy;
public int SelfStudy
{
get { return selfStudy; }
set { selfStudy = value; }
}
public SemesterDetails(string code,string name,int credits,int selfStudy)
{
this.ModuleCode = code;
this.ModuleName = name;
this.ModuleCredits = credits;
this.SelfStudy = selfStudy;
}
Try this
action
using Microsoft.AspNetCore.Mvc.Rendering;
.....
public ActionResult EditStudyHrs(User user)
{
var list= dataHandle.Read(user).ToList();
ViewBag.Modules = list.Select(i=> new SelectListItem { Value=i.ModuleCode, Text = i.ModuleName}).ToList();
var model= new SemesterDetails ();
return View(model);
}
view
#model SemesterDetails
.....
#Html.DropDownListFor(m => m.ModuleCode,#ViewBag.Modules, "Select Module")
or new syntax
<select class="form-control" asp-for="#Model.ModuleCode" asp-items="#ViewBag.Modules"></select>
Related
I have dataTreeListView named dataTreeListView1 i wish to get the name of the node which i clicked can any one please help me to do this
in the above picture if i click yes i wish to get yes on messagebox
what i tried to do is
private void dataTreeListView1_AfterSelect(object sender, EventArgs e)
{
MessageBox.Show("hello");
}
and the node are loaded dynamically means they are from database.
List<Class3> list = new List<Class3>();
list = Class3.GetList(startDate, endDate, con);
this.dataTreeListView1.ParentKeyAspectName = "ParentId";
this.dataTreeListView1.RootKeyValueString = "NUll";
BrightIdeasSoftware.OLVColumn col = new BrightIdeasSoftware.OLVColumn();
col.Width = 10;
dataTreeListView1.DataSource = list;
foreach (ColumnHeader column in this.dataTreeListView1.Columns)
{
column.Width = 140 + 140 + this.dataTreeListView1.SmallImageSize.Width;
}
this.dataTreeListView1.Columns.RemoveByKey("Id");
this.dataTreeListView1.Columns.RemoveByKey("ParentId");
this is how i show data in datatreelist view
public Class3()
{
this.xName = "";
this.xId = "";
this.xParentId = "";
this.xcredit = 0.0M;
this.xdebit = 0.0M;
this.xx = 0.0M;
this.xy = 0.0M;
}
public String Ledger
{
get { return this.xName; }
set { this.xName = value; }
}
public String Id
{
get { return this.xId; }
set { this.xId = value; }
}
public String ParentId
{
get { return this.xParentId; }
set { this.xParentId = value; }
}
public Decimal Credit
{
get { return this.xcredit; }
set { this.xcredit = value; }
}
public Decimal Debit
{
get { return this.xdebit; }
set { this.xdebit = value; }
}
public decimal x
{
get { return this.xx; }
set { this.xx = value; }
}
public decimal y
{
get { return this.xy; }
set { this.xy = value; }
}
public static List<Class3> GetList(DateTime startDate, DateTime endDate, SqlConnection con)
{
List<Class3> oList = new List<Class3>();
Buisiness b = new Buisiness();
try
{
decimal totalcredit = 0;
decimal totaldebit = 0;
con.Open();
// // Make sql readable
DataTable dt = new DataTable();
string sql = #"Select Ledger.LedId,Ledger.LedName,Ledger.MasterLedger from Ledger where Ledger.Date >= #prmStartDate and Ledger.Date <= #prmEndDate group by Ledger.MasterLedger,Ledger.LedId,Ledger.LedName";
// wrap IDisposable (SqlCommand) into using
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#prmStartDate", SqlDbType.DateTime).Value = startDate;
cmd.Parameters.Add("#prmEndDate", SqlDbType.DateTime).Value = endDate;
SqlDataReader da = cmd.ExecuteReader();
while (da.Read())
{
Class3 oClass = new Class3();
oClass.Ledger = da["LedName"].ToString();
oClass.Id = da["LedId"].ToString();
oClass.ParentId = da["MasterLedger"].ToString();
Dictionary<string, decimal> d = b.findclosingbalanceofledger(da["LedId"].ToString());
/* if (da["MasterLedger"].ToString() == "NUll")
{
oClass.Debit = findsumofallchilds(da["LedId"].ToString(), con, startDate, endDate);
}
else
{*/
if (d.FirstOrDefault().Key == "debit")
{
d.FirstOrDefault().Value.ToString();
d.FirstOrDefault().Value.ToString();
totaldebit = totaldebit + d.FirstOrDefault().Value;
oClass.Debit = d.FirstOrDefault().Value;
}
else if (d.FirstOrDefault().Key == "credit")
{
d.FirstOrDefault().Value.ToString();
totalcredit = totalcredit + d.FirstOrDefault().Value;
oClass.Credit = d.FirstOrDefault().Value;
}
/* }*/
oList.Add(oClass);
}
}
con.Close();
}
catch (Exception exe)
{
MessageBox.Show(exe.Message);
}
finally
{
con.Close();
}
return oList;
}
i have changed my code this
private void dataTreeListView1_AfterSelect(object sender, EventArgs e)
{
MessageBox.Show("hello");
}
to
private void dataTreeListView1_CellClick(object sender, CellClickEventArgs e)
{
MessageBox.Show("helo");
}
but no change
I'm still quite new to ASP.NET-MVC so i'm still a bit confused about returns and redirects and DropDownListFor values.
I have a view where a user inserts data to add to a database. Most of the data comes from DropDownLists, where the Lists are stored in the model. The lists are initiated once you enter the page for the first time, filling the model. Once you submit, the HttpPost on the Controller has a "ModelState.IsValid", and returns to the same page with the errors. The problem is, all the lists i had filled are now empty and the DropDownListFor are all empty.
Is there a way to keep the model with its values? Also, is there a way to keep the values previously entered on a DropDownListFor on return?
View Code:
#using Encomendas_WebFinal.Models
#{
ViewBag.Title = "Encomenda";
}
#model ClientModel
<link rel="stylesheet" href="~/Content/zebra_datepicker.min.css" />
<script src="~/Scripts/zebra_datepicker.min.js"></script>
<h1>Encomenda</h1>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-group">
<h3>Encomenda:</h3>
<fieldset>
<p>#Html.DropDownListFor(m => m.SelectedEncomenda.NumEncomenda, Model.ListEncomendas, "")</p>
#Html.ValidationMessageFor(m => m.SelectedEncomenda.NumEncomenda)
</fieldset>
<h3>Data:</h3>
#Html.EditorFor(m => m.SelectedEncomenda.Data, new { htmlAttributes = new { #class = "calendar"} })
<h3>Tipo de Infraestrutura:</h3>
<input type="radio" name="selectedLinhaType" id="150KV"/> 150kV <br>
<input type="radio" name="selectedLinhaType" id="220KV"/> 220KV <br>
<input type="radio" name="selectedLinhaType" id="400KV"/> 440KV <br>
<input type="radio" name="selectedLinhaType" id="Gasodutos" /> Gasodutos <br>
<input type="radio" name="selectedLinhaType" id="Patrimonios" /> Patrimonios <br>
<div class ="infobox" id="is150KV">
<fieldset>
<h3>Linha 150KV:</h3>
<p>#Html.DropDownListFor(m => m.SelectedLinha.NumLinha, Model.ListLinha150, new { disabled = "disabled", #id="Linha150KV"})</p>
</fieldset>
</div>
<div class ="infobox" id="is220KV">
<fieldset>
<h3>Linha 220KV:</h3>
<p>#Html.DropDownListFor(m => m.SelectedLinha.NumLinha, Model.ListLinha220, new { disabled = "disabled", #id = "Linha220KV" })</p>
</fieldset>
</div>
<div class="infobox" id="is400KV">
<fieldset>
<h3>Linha 400KV:</h3>
<p>#Html.DropDownListFor(m => m.SelectedLinha.NumLinha, Model.ListLinha400 as List<SelectListItem>, new { disabled = "disabled", #id = "Linha400KV" })</p>
</fieldset>
</div>
<div class="infobox" id="isGasoduto">
<fieldset>
<h3>Gasoduto:</h3>
<p>#Html.DropDownListFor(m => m.SelectedLinha.NumLinha, Model.ListGasodutos, new { disabled = "disabled", #id = "Gasoduto" })</p>
</fieldset>
</div>
<div class="infobox" id="isPatrimonio">
<h4> Patrimonio Selected</h4>
</div>
</div>
<h3>Concelho:</h3>
<fieldset>
<p>#Html.DropDownListFor(m => m.SelectedConcelho, Model.ListConcelhos, "")</p>
</fieldset>
<h3>Numero de Tecnicos de Aviso: #Html.TextBoxFor(m => m.SelectedEncomenda.TecnicoAvisoNum, new { type = "number", min = "0", max = "3", step = "1", value = "0", #id="TecnicoAvisoNum" }) </h3>
<div class="infobox" id="TecnicoAviso1">
<h4> Tecnico Aviso 1</h4>
</div>
<div class="infobox" id="TecnicoAviso2">
<h4> Tecnico Aviso 2</h4>
</div>
<div class="infobox" id="TecnicoAviso3">
<h4> Tecnico Aviso 3</h4>
</div>
<div class="infobox" id="TecnicoAvisoErro">
<h2> Por favor insira um valor inteiro entre 0 e 3.</h2>
</div>
<input type="submit" value="Post" />
#section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
$('.calendar').Zebra_DatePicker({
show_week_number: 'Wk',
format: 'd/m/Y'
});
$('#is150KV').hide(); $('#is220KV').hide(); $('#is400KV').hide(); $('#isGasoduto').hide(); $('#isPatrimonio').hide();
$('#TecnicoAviso1').hide(); $('#TecnicoAviso2').hide(); $('#TecnicoAviso3').hide(); $('#TecnicoAvisoErro').hide();
$('#150KV').change(function () {
$('#is220KV').hide(); $('#is400KV').hide(); $('#isGasoduto').hide(); $('#isPatrimonio').hide();
$('#is150KV').show();
$('#Linha220KV').attr('disabled', true); $('#Linha400KV').attr('disabled', true); $('#Gasoduto').attr('disabled', true);
$('#Linha150KV').removeAttr('disabled');
});
$('#220KV').change(function () {
$('#is150KV').hide(); $('#is400KV').hide(); $('#isGasoduto').hide(); $('#isPatrimonio').hide();
$('#is220KV').show();
$('#Linha150KV').attr('disabled', true); $('#Linha400KV').attr('disabled', true); $('#Gasoduto').attr('disabled', true);
$('#Linha220KV').removeAttr('disabled');
});
$('#400KV').change(function () {
$('#is150KV').hide(); $('#is220KV').hide(); $('#isGasoduto').hide(); $('#isPatrimonio').hide();
$('#is400KV').show();
$('#Linha150KV').attr('disabled', true); $('#Linha220KV').attr('disabled', true); $('#Gasoduto').attr('disabled', true);
$('#Linha400KV').removeAttr('disabled');
});
$('#Gasodutos').change(function () {
$('#is150KV').hide(); $('#is220KV').hide(); $('#is400KV').hide(); $('#isPatrimonio').hide();
$('#isGasoduto').show();
$('#Linha150KV').attr('disabled', true); $('#Linha220KV').attr('disabled', true); $('#Linha400KV').attr('disabled', true);
$('#Gasoduto').removeAttr('disabled');
});
$('#TecnicoAvisoNum').change(function () {
if ($('#TecnicoAvisoNum').val() == 0) {
$('#TecnicoAviso1').hide(); $('#TecnicoAviso2').hide(); $('#TecnicoAviso3').hide(); $('#TecnicoAvisoErro').hide();
}
else
if ($('#TecnicoAvisoNum').val() == 1) {
$('#TecnicoAviso1').show(); $('#TecnicoAviso2').hide(); $('#TecnicoAviso3').hide(); $('#TecnicoAvisoErro').hide();
}
else
if ($('#TecnicoAvisoNum').val() == 2) {
$('#TecnicoAviso1').hide(); $('#TecnicoAviso2').show(); $('#TecnicoAviso3').hide(); $('#TecnicoAvisoErro').hide();
}
else
if ($('#TecnicoAvisoNum').val() == 3) {
$('#TecnicoAviso1').hide(); $('#TecnicoAviso2').hide(); $('#TecnicoAviso3').show(); $('#TecnicoAvisoErro').hide();
}
else
{
$('#TecnicoAviso1').hide(); $('#TecnicoAviso2').hide(); $('#TecnicoAviso3').hide(); $('#TecnicoAvisoErro').show();
}
});
})
</script>
}
}
Controller:
using Encomendas_WebFinal.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
namespace Encomendas_WebFinal.Controllers
{
public class EncomendaController : BaseController
{
ClientModel cliente = new ClientModel();
ConcelhosModel concelhos = new ConcelhosModel();
//DB CONNECTION STRING
private static string GetSQLConnectionString()
{
string cstr =
"Server=localhost;Database=REN_Encomendas;User Id=admin;Password=admin;";
return cstr;
}
//GET DB TABLE
private static DataSet ExecuteQuery(string query)
{
SqlConnection dbConnection;
SqlCommand dbCommand;
DataSet objDataSet;
SqlDataAdapter objAdapter;
dbConnection = new SqlConnection();
dbConnection.ConnectionString = GetSQLConnectionString();
dbConnection.Open();
objAdapter = new SqlDataAdapter();
objDataSet = new DataSet();
dbCommand = new SqlCommand(query);
dbCommand.Connection = dbConnection;
objAdapter.SelectCommand = dbCommand;
objAdapter.Fill(objDataSet);
dbCommand.Dispose();
objAdapter.Dispose();
dbConnection.Dispose();
dbConnection.Close();
return objDataSet;
}
//GET PostEncomenda
public ActionResult PostEncomenda()
{
//Initiate Data
cliente.ListaEncomendas = GetEncomendasList();
concelhos.Nomes = GetConcelhos();
concelhos.Linhas150 = GetLinhas("150");
concelhos.Linhas220 = GetLinhas("220");
concelhos.Linhas400 = GetLinhas("400");
concelhos.Gasoduto = GetGasodutos();
//Makes a DropDownList for Encomendas
List<SelectListItem> ListEncomenda = new List<SelectListItem>();
for (int i = 0; i< cliente.ListaEncomendas.Count; i++)
{
ListEncomenda.Add(new SelectListItem
{
Text = cliente.ListaEncomendas[i].NumEncomenda.ToString() + " -- " + cliente.ListaEncomendas[i].NomeEncomenda,
Value = cliente.ListaEncomendas[i].NumEncomenda.ToString() + "-_-_-" + cliente.ListaEncomendas[i].NomeEncomenda,
});
}
//Makes a DropDownList for Linhas
List<SelectListItem> ListLinhas150 = new List<SelectListItem>();
for (int i = 0; i< concelhos.Linhas150.Count; i++)
{
ListLinhas150.Add(new SelectListItem
{
Text = concelhos.Linhas150[i].NumLinha + " -- " + concelhos.Linhas150[i].NomeLinha,
Value = concelhos.Linhas150[i].NumLinha + "-_-_-" + concelhos.Linhas150[i].NomeLinha,
});
}
List<SelectListItem> ListLinhas220 = new List<SelectListItem>();
for (int i = 0; i < concelhos.Linhas220.Count; i++)
{
ListLinhas220.Add(new SelectListItem
{
Text = concelhos.Linhas220[i].NumLinha + " -- " + concelhos.Linhas220[i].NomeLinha,
Value = concelhos.Linhas220[i].NumLinha + "-_-_-" + concelhos.Linhas220[i].NomeLinha,
});
}
List<SelectListItem> ListLinhas400 = new List<SelectListItem>();
for (int i = 0; i < concelhos.Linhas400.Count; i++)
{
ListLinhas400.Add(new SelectListItem
{
Text = concelhos.Linhas400[i].NumLinha + " -- " + concelhos.Linhas400[i].NomeLinha,
Value = concelhos.Linhas400[i].NumLinha + "-_-_-" + concelhos.Linhas400[i].NomeLinha,
});
}
//Makes a DropDownList for Gasodutos
List<SelectListItem> ListGasodutos = new List<SelectListItem>();
for (int i = 0; i < concelhos.Gasoduto.Count; i++)
{
ListGasodutos.Add(new SelectListItem
{
Text = concelhos.Gasoduto[i].NumLinha + " -- " + concelhos.Gasoduto[i].NomeLinha,
Value = concelhos.Gasoduto[i].NumLinha + "-_-_-" + concelhos.Gasoduto[i].NomeLinha,
});
}
//Makes a DropDownList for Concelhos
List<SelectListItem> ListConcelhos = new List<SelectListItem>();
for (int i = 0; i < concelhos.Nomes.Count; i++)
{
ListConcelhos.Add(new SelectListItem
{
Text = concelhos.Nomes[i],
Value = concelhos.Nomes[i]
});
}
cliente.ListLinha150 = ListLinhas150;
cliente.ListLinha220 = ListLinhas220;
cliente.ListLinha400 = ListLinhas400;
cliente.ListGasodutos = ListGasodutos;
cliente.ListConcelhos = ListConcelhos;
cliente.ListEncomendas = ListEncomenda;
cliente.SelectedEncomenda = new PostEncomendaModel();
return View(cliente);
}
//POST PostEncomenda
[HttpPost]
public ActionResult PostEncomenda(ClientModel viewModel)
{
if(ModelState.IsValid)
{
//Test Stuff
PostEncomendaModel encomenda = new PostEncomendaModel();
string[] encomendaNumNome = viewModel.SelectedEncomenda.NumEncomenda.Split(new[] { "-_-_-" }, StringSplitOptions.None);
encomenda.NumEncomenda = encomendaNumNome[0];
encomenda.NomeEncomenda = encomendaNumNome[1];
encomendaNumNome = viewModel.SelectedLinha.NumLinha.Split(new[] { "-_-_-" }, StringSplitOptions.None);
encomenda.Linha = new Linhas();
encomenda.Linha.NomeLinha = encomendaNumNome[0];
encomenda.Linha.NumLinha = encomendaNumNome[1];
encomenda.Data = viewModel.SelectedEncomenda.Data;
TempData["Encomenda"] = encomenda;
return RedirectToAction("Teste", "Encomenda");
}
return View(viewModel);
}
//GET Submit Test
[HttpGet]
public ActionResult Teste(PostEncomendaModel model)
{
PostEncomendaModel encomenda = new PostEncomendaModel();
encomenda = (PostEncomendaModel)TempData["Encomenda"];
ViewBag.EncomendaNum = encomenda.NumEncomenda;
ViewBag.EncomendaNome = encomenda.NomeEncomenda;
ViewBag.LinhaNum = encomenda.Linha.NumLinha;
ViewBag.LinhaNome = encomenda.Linha.NomeLinha;
ViewBag.Data = Convert.ToDateTime(encomenda.Data);
DateTime tempdata = ViewBag.Data;
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(tempdata);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
tempdata = tempdata.AddDays(3);
}
ViewBag.Semana = CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(tempdata, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return View();
}
//GET ALL ENCOMENDAS FROM DB FOR THE SELECTED CLIENT LOGGED ON
public IList<EncomendaModel> GetEncomendasList()
{
IList<EncomendaModel> encomendas= new List<EncomendaModel>();
//GET Encomenda Name && Number
string username = HttpContext.Request.Cookies.Get("nome").Value;
string query = "SELECT * FROM dbo.renland_encomenda AS child WHERE child.coordenad LIKE '" + username + "%'"; //Meter User.Identity.GetUserName(); aqui
DataSet table_encomendas = ExecuteQuery(query);
foreach (DataRow r in table_encomendas.Tables[0].Rows)
{
if (Convert.ToInt32(r[2]) == 1) //Se Encomenda esta ativa
{
EncomendaModel tEnco = new EncomendaModel();
string numEnco = r[0].ToString();
tEnco.NumEncomenda = r[1].ToString();
tEnco.NomeEncomenda = r[3].ToString();
encomendas.Add(tEnco);
}
}
query = "SELECT numero, ativa, prest_serv FROM dbo.renland_encomenda_patrimonio AS child WHERE child.coordenad LIKE '"+ username +"%'";
DataSet table_encomendas2 = ExecuteQuery(query);
foreach (DataRow r in table_encomendas2.Tables[0].Rows)
{
if (Convert.ToInt32(r[1]) == 1) //Se Encomenda esta ativa
{
EncomendaModel tEnco = new EncomendaModel();
string numEnco = r[0].ToString();
tEnco.NumEncomenda = r[0].ToString();
tEnco.NomeEncomenda = r[2].ToString();
encomendas.Add(tEnco);
}
}
return encomendas;
}
//GET ALL CONCELHOS
public IList<string> GetConcelhos()
{
IList<string> concelhos = new List<string>();
string query = "SELECT Concelho FROM dbo.Concelhos";
DataSet table = ExecuteQuery(query);
foreach(DataRow r in table.Tables[0].Rows)
{
concelhos.Add(r[0].ToString());
}
return concelhos;
}
//GET ALL LINHAS
public IList<Linhas> GetLinhas(string num)
{
IList<Linhas> tlinha = new List<Linhas>();
string query = "SELECT DISTINCT ID_LN FROM dbo.RENLAND_PLANOMANUTENCAOFAIXA AS child WHERE child.N_TENSAO LIKE '"+num+ "%' ORDER BY ID_LN ASC";
string query2 = "SELECT ID_LN, DESCR_LN FROM dbo.SEGMENTOS_RNT WHERE ID_LN LIKE '%' ORDER BY ID_LN ASC";
DataSet table = ExecuteQuery(query);
DataSet table2 = ExecuteQuery(query2);
foreach (DataRow r in table.Tables[0].Rows)
{
Linhas tl = new Linhas();
tl.NumLinha= r[0].ToString();
foreach (DataRow r2 in table2.Tables[0].Rows)
{
if (tl.NumLinha== r2[0].ToString())
{
tl.NomeLinha = r2[1].ToString();
break;
}
}
tlinha.Add(tl);
}
return tlinha;
}
//GET ALL GASODUTOS
public IList<Linhas> GetGasodutos()
{
IList<Linhas> tlinha = new List<Linhas>();
string query = "SELECT ID_GD, DEN_GD FROM dbo.Gasodutos_RNTGN ";
DataSet table = ExecuteQuery(query);
foreach (DataRow r in table.Tables[0].Rows)
{
Linhas tl = new Linhas();
tl.NumLinha = r[0].ToString();
tl.NomeLinha = r[1].ToString();
tlinha.Add(tl);
}
return tlinha;
}
}
}
Client Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Encomendas_WebFinal.Models;
using System.Web.Mvc;
namespace Encomendas_WebFinal.Models
{
public class ClientModel
{
private IList<EncomendaModel> listaEncomendas = new List<EncomendaModel>();
public IList<EncomendaModel> ListaEncomendas { get { return listaEncomendas; } set { listaEncomendas = value; } }
public PostEncomendaModel SelectedEncomenda { get; set; }
public Linhas SelectedLinha { get; set; }
public string SelectedConcelho { get; set; }
List<SelectListItem> _listEncomendas = new List<SelectListItem>();
public List<SelectListItem> ListEncomendas { get { return _listEncomendas; } set { _listEncomendas = value; } }
List<SelectListItem> _listLinha150 = new List<SelectListItem>();
public List<SelectListItem> ListLinha150 { get { return _listLinha150; } set { _listLinha150 = value; } }
List<SelectListItem> _listLinha220 = new List<SelectListItem>();
public List<SelectListItem> ListLinha220 { get { return _listLinha220; } set { _listLinha220 = value; } }
List<SelectListItem> _listLinha400 = new List<SelectListItem>();
public List<SelectListItem> ListLinha400 { get { return _listLinha400; } set { _listLinha400 = value; } }
List<SelectListItem> _listGasodutos = new List<SelectListItem>();
public List<SelectListItem> ListGasodutos { get { return _listGasodutos; } set { _listGasodutos = value; } }
List<SelectListItem> _listPatrimonios = new List<SelectListItem>();
public List<SelectListItem> ListPatrimonios { get { return _listPatrimonios; } set { _listPatrimonios = value; } }
List<SelectListItem> _listConcelhos = new List<SelectListItem>();
public List<SelectListItem> ListConcelhos { get { return _listConcelhos; } set { _listConcelhos = value; } }
}
}
PostEncomendaModel Model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace Encomendas_WebFinal.Models
{
public class PostEncomendaModel
{
//Not all data annotations are complete
[Required]
[Display(Name = "Encomenda")]
public string NumEncomenda { get; set; }
[Display(Name = "Nome da Encomenda")]
public String NomeEncomenda { get; set; }
[Required]
[Display(Name = "Linha")]
public Linhas Linha { get; set; }
[Required]
public string Data { get; set; }
public int Semana { get; set; }
[Display(Name = "Vãos")]
public String Vaos { get; set; }
private IList<String> _concelho = new List<String>();
[Display(Name = "Concelho")]
[Required]
public IList<String> Concelho { get { return _concelho; } set { _concelho = value; } }
public int TecnicoAvisoNum { get; set; }
public int EquipaCampoNum { get; set; }
private IList<String> _tecnicoAviso = new List<String>(3);
[Display(Name = "Tecnico de Aviso")]
public IList<String> TecnicoAviso { get { return _tecnicoAviso; } set { _tecnicoAviso = value; } }
private IList<String> _equipaCampo = new List<String>(3);
[Display(Name = "Equipa de Campo")]
public IList<String> EquipaCampo { get { return _equipaCampo; } set { _equipaCampo = value; } }
private IList<String> _tecnicoAvisoTel = new List<String>(3);
[Display(Name = "Telefone Tecnico")]
public IList<String> TecnicoAvisoTel { get { return _tecnicoAvisoTel; } set { _tecnicoAvisoTel = value; } }
private IList<String> _equipaCampoTel = new List<String>(3);
[Display(Name = "Telefone Equipa")]
public IList<String> EquipaCampoTel { get { return _equipaCampoTel; } set { _equipaCampoTel = value; } }
[Display(Name = "Email")]
public String Email { get; set; }
[Display(Name = "Observações")]
public String Observacoes { get; set; }
}
}
Your radios are like:
<input type="radio" name="selectedLinhaType" id="150KV"/> 150kV <br>
Where the name is selectedLinhaType. This name doesn't match up with any property on your view model, so any posted values will simply be discarded by the model binder. The name must match the name of the property you want the value to bind to. You could manually change the name attribute on these, but the better approach is to let Razor handle it:
#Html.RadioButtonFor(m => m.MyProperty, "foo")
Where MyProperty is the property you want to bind to the posted value to, and "foo" is the value this radio button should have.
I want to delete the row by its Id but I cant delete it by its Id.like for example the values are
date|time|Floor|zone|Latitude|longitude and I want to delete a row of its while selecting it but i cannot.below is the class where i wrote all main functions
public class DbHelper
{
SQLiteConnection dbConn;
public async Task<bool> onCreate(string DB_PATH)
{
try
{
if (!CheckFileExists(DB_PATH).Result)
{
using (dbConn = new SQLiteConnection(DB_PATH))
{
dbConn.CreateTable<historyTableSQlite>();
}
}
return true;
}
catch
{
return false;
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
return false;
}
}
//retrieve all list from the database
public ObservableCollection<historyTableSQlite> ReadHistory()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
List<historyTableSQlite> myCollection = dbConn.Table<historyTableSQlite>().ToList<historyTableSQlite>();
ObservableCollection<historyTableSQlite> HistoryList = new ObservableCollection<historyTableSQlite>(myCollection);
return HistoryList;
}
}
// Insert the new info in the histrorytablesqlite table.
public void Insert(historyTableSQlite newcontact)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
dbConn.RunInTransaction(() =>
{
dbConn.Insert(newcontact);
});
}
}
public void AddInfo()
{
//string f = Checkin.Floor_st;
Debug.WriteLine(Checkin.a);
string z = Checkin.Zone_st;
DbHelper Db_helper = new DbHelper();
Db_helper.Insert((new historyTableSQlite
{
Date = DateTime.Now.ToShortDateString(),
Time = DateTime.Now.ToShortTimeString(),
Zone = "D",
Floor = "7",
latitude =12344.66,
longtitude = -122.56
}));
}
// Delete specific contact
public void DeleteContact(int Id)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
var existingvalue = dbConn.Query<historyTableSQlite>("select * from historyTableSQlite where Id =" + Id).FirstOrDefault();
if (existingvalue != null)
{
dbConn.RunInTransaction(() =>
{
dbConn.Delete(existingvalue);
});
}
}
}
//Delete all contactlist or delete Contacts table
public void DeleteAllContact()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
//dbConn.RunInTransaction(() =>
// {
dbConn.DropTable<historyTableSQlite>();
dbConn.CreateTable<historyTableSQlite>();
dbConn.Dispose();
dbConn.Close();
//});
}
}
}
below is the class where I show the values
public partial class History : PhoneApplicationPage
{
ObservableCollection<historyTableSQlite> DB_HistoryList = new ObservableCollection<historyTableSQlite>();
DbHelper Db_helper = new DbHelper();
//int Selected_HistoryId;
public static int Selected_HistoryId { get; set; }
// string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
public History()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Db_helper.AddInfo();
ReadHistoryList_Loaded();
// Selected_HistoryId = int.Parse(NavigationContext.QueryString["SelectedHistoryID"]);
}
public void ReadHistoryList_Loaded()
{
ReadAllContactsList dbhistory = new ReadAllContactsList();
DB_HistoryList = dbhistory.GetAllHistory();//Get all DB contacts
ListData.ItemsSource = DB_HistoryList.OrderByDescending(i => i.Id).ToList();
//Latest contact ID can Display first
}
public void ListData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListData.SelectedIndex != -1)
{
historyTableSQlite listitem = ListData.SelectedItem as historyTableSQlite;
int Selected_HistoryId = listitem.Id;
}
}
public void Delete_Click(object sender, EventArgs e)
{
Db_helper.DeleteContact(Selected_HistoryId);
}
private void DeleteAll_Click(object sender, EventArgs e)
{
DbHelper Db_helper = new DbHelper();
Db_helper.DeleteAllContact();//delete all db
DB_HistoryList.Clear();
ListData.ItemsSource = DB_HistoryList;
}
//public void updateDB(string fl,string zo,double la, double lo)
//{
// using (var db = new SQLiteConnection(dbPath))
// {
// var existing = db.Query<historyTableSQlite>("select * from historyTableSQlite").FirstOrDefault();
// if (existing != null)
// {
// existing.Floor = fl;
// existing.Zone = zo;
// existing.latitude = la;
// existing.longtitude = lo;
// db.RunInTransaction(() =>
// {
// db.Update(existing);
// });
// }
// }
//}
//public void AddDb(string fl, string zo, double la, double lo)
//{
// string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
// using (var db = new SQLiteConnection(dbPath))
// {
// db.RunInTransaction(() =>
// {
// db.Insert(new historyTableSQlite()
// {
// Date = DateTime.Today.ToShortDateString(),
// Time = DateTime.Now.ToShortTimeString(),
// Floor = fl,
// Zone = zo,
// longtitude = la,
// latitude = lo
// });
// Debug.WriteLine(db);
// });
// }
}
I am updating the table class so that it is easy to understand
public class historyTableSQlite : INotifyPropertyChanged
{
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int Id { get; set; }
private int idvalue;
private string dateValue = string.Empty;
public string Date {
get { return this.dateValue; }
set
{
if (value != this.dateValue)
{
this.dateValue = value;
NotifyPropertyChanged("Date");
}
}
}
private string timeValue = string.Empty;
public string Time
{
get { return this.timeValue; }
set
{
if (value != this.timeValue)
{
this.timeValue = value;
NotifyPropertyChanged("Time");
}
}
}
private string floorValue = string.Empty;
public string Floor
{
get { return this.floorValue; }
set
{
if (value != this.floorValue)
{
this.floorValue = value;
NotifyPropertyChanged("Floor");
}
}
}
public string zoneValue;
public string Zone
{
get { return this.zoneValue; }
set
{
if (value != this.zoneValue)
{
this.zoneValue = value;
NotifyPropertyChanged("Zone");
}
}
}
private double latValue;
public double latitude
{
get { return latValue; }
set
{
if (value != this.latValue)
{
this.latValue = value;
NotifyPropertyChanged("Latitude");
}
}
}
private double lonValue;
public double longtitude
{
get { return this.lonValue; }
set
{
if (value != this.lonValue)
{
this.lonValue = value;
NotifyPropertyChanged("Longitude");
}
}
}
// public string isMarkPoint { get; set; }
public historyTableSQlite()
{
}
public historyTableSQlite(string date,string time,string floor,string zone,double lat,double lng)
{
Date = date;
Time = time;
Floor = floor;
Zone = zone;
latitude = lat;
longtitude = lng;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
when i click the delete i.e the method delete_click i cant delete the row
EDIT: I cut and pasted your code incorrectly...you have very poor alignment :)
Okay I think I finally got your code to run, your problem is here
public void ListData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListData.SelectedIndex != -1)
{
historyTableSQlite listitem = ListData.SelectedItem as historyTableSQlite;
// this will get destroy when the function exits, it's local decalartion
int Selected_HistoryId = listitem.Id;
// History.Selected_HistoryId = listitem.Id;
// you need to set the Property not a local variable
}
}
you made a local variable named the same as the Property it should be
History.Selected_HistoryId = listitem.Id;
public void Delete_Click(object sender, EventArgs e)
{
Db_helper.DeleteContact(History.Selected_HistoryId);
}
I am developing an windows phone app using sqlite database.I am able to show out the database and delete the particular row I want to delete.But the problem is after I select the row and click delete the row does not vanishes at that time.I have to renter that page to see that it is deleted.
Below here is the code of the class where I use the click_delete event
public partial class History : PhoneApplicationPage
{
ObservableCollection<historyTableSQlite> DB_HistoryList = new ObservableCollection<historyTableSQlite>();
DbHelper Db_helper = new DbHelper();
//public static int Selected_HistoryId;
//int Selected_HistoryId;
public static int Selected_HistoryId {get; set;}
// string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
public History()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Db_helper.AddInfo();
ReadHistoryList_Loaded();
// Selected_HistoryId = int.Parse(NavigationContext.QueryString["SelectedHistoryID"]);
}
public void ReadHistoryList_Loaded()
{
ReadAllContactsList dbhistory = new ReadAllContactsList();
DB_HistoryList = dbhistory.GetAllHistory();//Get all DB contacts
ListData.ItemsSource = DB_HistoryList.OrderByDescending(i => i.Id).ToList();
//Latest contact ID can Display first
}
public void ListData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListData.SelectedIndex != -1)
{
historyTableSQlite listitem = ListData.SelectedItem as historyTableSQlite;
History.Selected_HistoryId = listitem.Id;
}
}
private void Delete_Click(object sender, EventArgs e)
{
Db_helper.DeleteContact(History.Selected_HistoryId);
NavigationService.Navigate(new Uri("/History.xaml", UriKind.Relative));
}
private void DeleteAll_Click(object sender, EventArgs e)
{
DbHelper Db_helper = new DbHelper();
Db_helper.DeleteAllContact();//delete all DB contacts
DB_HistoryList.Clear();//Clear collections
ListData.ItemsSource = DB_HistoryList;
}
}
}
below is the class with all main functions
public class DbHelper
{
SQLiteConnection dbConn;
public async Task<bool> onCreate(string DB_PATH)
{
try
{
if (!CheckFileExists(DB_PATH).Result)
{
using (dbConn = new SQLiteConnection(DB_PATH))
{
dbConn.CreateTable<historyTableSQlite>();
}
}
return true;
}
catch
{
return false;
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
return false;
}
}
//retrieve all list from the database
public ObservableCollection<historyTableSQlite> ReadHistory()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
List<historyTableSQlite> myCollection = dbConn.Table<historyTableSQlite>().ToList<historyTableSQlite>();
ObservableCollection<historyTableSQlite> HistoryList = new ObservableCollection<historyTableSQlite>(myCollection);
return HistoryList;
}
}
// Insert the new info in the histrorytablesqlite table.
public void Insert(historyTableSQlite newcontact)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
dbConn.RunInTransaction(() =>
{
dbConn.Insert(newcontact);
});
}
}
public void AddInfo()
{
DbHelper Db_helper = new DbHelper();
Db_helper.Insert((new historyTableSQlite
{
Date = DateTime.Now.ToShortDateString(),
Time = DateTime.Now.ToShortTimeString(),
Zone = Checkin.Zone_st,
Floor = Checkin.Floor_st,
latitude = Checkin.Latitud_do,
longtitude = Checkin.Longtitude_do
}));
}
// Delete specific contact
public void DeleteContact(int Id)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
var existingvalue = dbConn.Query<historyTableSQlite>("select * from historyTableSQlite where Id =" + Id).FirstOrDefault();
if (existingvalue != null)
{
dbConn.RunInTransaction(() =>
{
dbConn.Delete(existingvalue);
});
}
}
}
//Delete all contactlist or delete Contacts table
public void DeleteAllContact()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
//dbConn.RunInTransaction(() =>
// {
dbConn.DropTable<historyTableSQlite>();
dbConn.CreateTable<historyTableSQlite>();
dbConn.Dispose();
dbConn.Close();
//});
}
}
below is the class with all tables
public class historyTableSQlite : INotifyPropertyChanged
{
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int Id
{
get;
set;
}
private int idValue;
private string dateValue = string.Empty;
public string Date
{
get { return this.dateValue; }
set
{
if (value != this.dateValue)
{
this.dateValue = value;
NotifyPropertyChanged("Date");
}
}
}
private string timeValue = string.Empty;
public string Time
{
get { return this.timeValue; }
set
{
if (value != this.timeValue)
{
this.timeValue = value;
NotifyPropertyChanged("Time");
}
}
}
private string floorValue = string.Empty;
public string Floor
{
get { return this.floorValue; }
set
{
if (value != this.floorValue)
{
this.floorValue = value;
NotifyPropertyChanged("Floor");
}
}
}
public string zoneValue;
public string Zone
{
get { return this.zoneValue; }
set
{
if (value != this.zoneValue)
{
this.zoneValue = value;
NotifyPropertyChanged("Zone");
}
}
}
private double latValue;
public double latitude
{
get { return latValue; }
set
{
if (value != this.latValue)
{
this.latValue = value;
NotifyPropertyChanged("Latitude");
}
}
}
private double lonValue;
public double longtitude
{
get { return this.lonValue; }
set
{
if (value != this.lonValue)
{
this.lonValue = value;
NotifyPropertyChanged("Longitude");
}
}
}
// public string isMarkPoint { get; set; }
public historyTableSQlite()
{
}
public historyTableSQlite(string date, string time, string floor, string zone, double lat, double lng)
{
Date = date;
Time = time;
Floor = floor;
Zone = zone;
latitude = lat;
longtitude = lng;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
If you delete the item from your ObservableCollection, it will notify the ListBox to update its container.
In your code you have
// this is correct
ObservableCollection<historyTableSQlite> DB_HistoryList = new ObservableCollection<historyTableSQlite>();
But your problem is that you don't actually link your ListBox to it.
In your code you create a copy (and the worst kind of copy given what you're trying to do) and you set the ListBox ItemsSource to it. See below (you have this)
ListData.ItemsSource = DB_HistoryList.OrderByDescending(i => i.Id).ToList();
So basically, your ListBox is not an ObservableCollection but it's a List structure.
Deleting and Inserting into the List will not update the ListBox's UI.
Get rid of this List, find another way to sort your ObservableCollection.
Then you can basically do this
ListData.ItemsSource = DB_HistoryList; // set the listbox to the actual obs collection
DB_HistoryList.RemoveAt(i); // remove the item at index i
DB_HistoryList.RemoveItem(object); // remove the object that matches
I am writing code in C# where I want to select data in datagrid from multiple tables with a relation... Here I have a Client & Item_Configuration as parent table and Item_Order as child table which has the foreign keys from Client and Item_Configuration, I just want to fetch data from all three tables and display on a datagrid
My stored procedure is:
ALTER PROC [dbo].[Full_SP]
#clientName varchar(50) = null,
#itemName varchar(50) = null,
#clientId_FK varchar(50) = null,
#operation int
AS
BEGIN
SET NOCOUNT ON;
if #operation = 2
BEGIN
SELECT
Client.clintName, Item_Configuration.itemName,
Item_Order.orderId, Item_Order.orderDate, Item_Order.quantity,
Item_Order.status, Item_Order.totalPrice
FROM
Item_Order
INNER JOIN
Client ON Item_Order.clintId_FK = Client.clientId
JOIN
Item_Configuration ON Item_Order.itemId_FK = Item_Configuration.itemId
END
END
And my function of search to data grid is in C# i.e.
private void btnSrchFull_Click(object sender, EventArgs e)
{
SqlConnection conn1 = new SqlConnection();
try
{
conn1.ConnectionString = "server=.\\ms2k5;database=Info_Connect;Trusted_Connection=true";
conn1.Open();
SqlCommand selectFull = new SqlCommand("Full_SP", conn1);
selectFull.CommandType = CommandType.StoredProcedure;
selectFull.Parameters.Add("#operation", SqlDbType.VarChar);
selectFull.Parameters["#operation"].Value = 2;
SqlDataReader myReader = selectFull.ExecuteReader();
List<FullFill> list = new List<FullFill>();
while (myReader.Read())
{
if (myReader.HasRows)
{
FullFill fullfill = new FullFill();
fullfill = MapFullfill(myReader, fullfill);
list.Add(fullfill);
}
}
myReader.NextResult();
foreach (FullFill ffll in list)
{
if (myReader.Read() && myReader.HasRows)
{
MapClient(myReader, ffll);
}
}
myReader.NextResult();
foreach (FullFill ffll1 in list)
{
if (myReader.Read() && myReader.HasRows)
{
MapItem(myReader, ffll1);
}
}
dataGridView1.DataSource = list;
double totPrice = 0;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
totPrice = totPrice +
Convert.ToDouble(dataGridView1.Rows[i].Cells[5].Value);
totCost.Text = totPrice.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace + MessageBoxIcon.Error);
}
finally
{
if (conn1.State != ConnectionState.Closed)
{
conn1.Close();
}
}
}
private FullFill MapItem(SqlDataReader myReader, FullFill itemName)
{
itemName.ItemName =myReader["itemName"].ToString();
return itemName;
}
private FullFill MapClient(SqlDataReader myReader, FullFill clientName)
{
clientName.ClientName = myReader["clientName"].ToString();
return clientName;
}
private FullFill MapFullfill(SqlDataReader myReader, FullFill fullfill)
{
fullfill.OrderNo = myReader["orderId"].ToString();
fullfill.OrderDate = Convert.ToDateTime(myReader["orderDate"]);
fullfill.Quantity = Convert.ToInt32(myReader["quantity"]);
fullfill.Status = myReader["status"].ToString();
fullfill.TotalPrice = Convert.ToDouble(myReader["totalPrice"]);
return fullfill;
}
and I created a class for property i.e.
class FullFill
{
public string orderNo;
public string clientName;
public DateTime orderDate;
public string itemName;
public int quantity;
public double totCost;
public string status;
public string OrderNo { get { return orderNo; } set { orderNo = value; } }
public string ClientName { get { return clientName; } set { clientName = value; } }
public DateTime OrderDate { get { return orderDate; } set { orderDate = value; } }
public string ItemName { get { return itemName; } set { itemName = value; } }
public int Quantity { get { return quantity; } set { quantity = value; } }
public double TotalPrice { get { return totCost; } set { totCost = value; } }
public string Status { get { return status; } set { status = value; } }
}
}
The problem is that I am only able to find data from child table(Item_Order) I am not getting data from parent Tables.