Filling DropDownList from DataTable in Mvc C# - c#

connectionHelper.Select(query) returns datatable. I want to fill my dropdownlist in view with empList. How can I do it?
var query = "SELECT ADSOYAD, EMPLOYEE_NUMBER FROM TTF_PERSONEL";
var employeeNames = connectionHelper.Select(query);
var empList = new List<CalisanModels>();
var emp = new CalisanModels();
for (int i = 0; i < employeeNames.Rows.Count; i++)
{
var data = employeeNames.Rows[i];
emp.EmployeeNumber = Convert.ToInt32(data["EMPLOYEE_NUMBER"]);
emp.AdSoyad = data["ADSOYAD"].ToString();
empList.Add(emp);
}

So you have got your empList filled now you can send it to View where it can be rendered.
Set from your Action:
ViewBag.EmployeeList = empList;
Render in your view:
#Html.DropDownList("Employees", new SelectList((IEnumerable<MyMvcApp.CalisanModels>)ViewBag.EmployeeList, "EMPLOYEE_NUMBER", "ADSOYAD"))
Similar dropdown population in action I answered before here: https://dotnetfiddle.net/yPwHDB

Related

Alternate of Class Object while creating formatted List

I have a Datatable which is being added to List with specific format. Now as per my requirement I do not want to create generic list from a Class while preserving the format of my data but not able to do it. Below is my code
List<Data> datalist = new List<Data>();
for (int i = 0; i < dt.Rows.Count; i++)
{
Data dd1 = new Data();
dd1.ID = Convert.ToString(dt.Rows[i]["ID"]);
dd1.STATUS = Convert.ToString(dt.Rows[i]["Name"]);
dd1.TYPE = Convert.ToString(dt.Rows[i]["TYPE"]);
datalist.Add(dd1);
}
Is there a way to remove dependency of class Data from the above code keeping the format same?
You can use linq query on your dt like below and project your result into anonymous type like.
var datalist = (from r in dt.AsEnumerable()
select new
{
ID = r.Field<string>("ID"),
Name = r.Field<string>("Name"),
TYPE = r.Field<string>("TYPE"),
}).ToList();
If you want to get name for some Id from datalist then.
string name = datalist.Where(x => x.ID == "123").FirstOrDefault()?.Name;
You could use a dictionary in its place. No more Data class dependency, but the same basic data and format!
var datalist = new List<IDictionary<string, string>>();
for (var i = 0; i < dt.Rows.Count; ++i)
{
var data = new Dictionary<string, string>()
{
{ "ID", Convert.ToString(dt.Rows[i]["ID"]) },
{ "STATUS", Convert.ToString(dt.Rows[i]["Name"]) },
{ "TYPE", Convert.ToString(dt.Rows[i]["TYPE"]) }
};
datalist.Add(data);
}
Then you'd just access the values datalist[i]["ID"] instead of datalist[i].ID.

How to add the content of a combobox in a database

I want to add the content of the combobbox into my database, but it doesn't work. The content of my combobox is from the table 'Categories' who's joined with the table 'Products'. I've tried many things I have errors of conversion :
Here's my code :
Product p = new Product();
p.ProductName = txtNom.Text.Trim();
p.ProductDescription = txtDesc.Text.Trim();
p.ProductQuantityUsed = Convert.ToInt32(numQteUsed.Value);
p.ProductQuantityNew = Convert.ToInt32(numQteNew.Value);
p.CategoryID = cboCat.SelectedText.ToString();
db.Products.Add(p);
db.SaveChanges();
//Combobox
public void FillCbCategories()
{
SamsonEntities db = new SamsonEntities();
cboCat.Items.Clear();
var listCat = (from cats in db.Categories
select new CategoryDisplay()
{
CategoryID = cats.CategoryID,
CategoryName = cats.CategoryName
}).ToList();
for(var i=0;i<listCat.Count;i++)
{
cboCat.Items.Add(listCat[i]);
}
}
Judging by your comments, your combobox is not binded correctly to data you send to it.
You could try setting ValueMember and DisplayMember:
cboCat.ValueMember = "CategoryID";
cboCat.DisplayMember = "CategoryName";
in your method, like this:
public void FillCbCategories()
{
SamsonEntities db = new SamsonEntities();
cboCat.Items.Clear();
var listCat = (from cats in db.Categories
select new CategoryDisplay()
{
CategoryID = cats.CategoryID,
CategoryName = cats.CategoryName
}).ToList();
for(var i=0;i<listCat.Count;i++)
{
cboCat.Items.Add(listCat[i]);
}
cboCat.ValueMember = "CategoryID";
cboCat.DisplayMember = "CategoryName";
}

Populate a Listbox from a database

I want to fill my ListBox 'lstCategories' with the content of a database and all I see is nothing, here's the code :
public void FillCategories()
{
SamsonEntities db = new SamsonEntities();
var ListCats = (from cat in db.Categories
select new CategoryDisplay()
{
CategoryID = cat.CategoryID,
CategoyName = cat.CategoryName
}).ToList();
//for (var i = 0; i < db.Categories.Count();i++ )
//{
// lstCategories.Items.Add(....);
//}
}
I don't know what to place into the line of my 'for', so I put it in comments
Have you tried setting the list as the ListBox datasource?
lstCategories.DataSource = ListCats;
That should be enough.
As per your comment you need to set up the DisplayMember of your list to match the property to show:
lstCategories.DisplayMember = "CategoryName";
And you probably want to setup the ValueMember too:
lstCategories.ValueMember = "CategoryID";

GridView Column DataType as Value of DropDownList

Someone here earlier helped me get the code below that populates a dropdownlist with the column names and datatype of a GridView. Now I want the datatype to be the value of the dropdownlist and I'm not sure how to do it. Can anyone show me how?
public void ddlColumnPopulate()
{
var gvColumns = GridView1.Columns;
var viewName = ((IDataSource)EntityDataSource1).GetViewNames().OfType<string>().First();
var view = (EntityDataSourceView)((IDataSource)EntityDataSource1).GetView(viewName);
var schema = view.GetViewSchema();
var dsColumns = schema.Columns;
var dvColumnsDict = gvColumns.OfType<BoundField>().ToDictionary(a => a.DataField);
foreach (DataColumn c in dsColumns)
{
var li = new ListItem(string.Format("{0}: {1}", c.ColumnName, c.DataType), c.ColumnName);
ddlColumn.Items.Add(li);
}
}
I figured itout.
var li = new ListItem(string.Format("{0}: {1}", c.ColumnName, c.DataType), c.DataType.ToString());

Entity Framework add first row to database from a List?

foreach (StockItem item in StockList)
{
Master master = new Master();
master.VoucherNo = BillNo;
master.Voucher = "Sales";
master.StockName = StockList[0].StockName;
master.Quantity = StockList[0].Quantity;
master.Unit = StockList[0].Unit;
master.Price = StockList[0].UnitPrice;
master.Amount = StockList[0].Amount;
dbContext.AddToMasters(master);
dbContext.SaveChanges();
}
Sale sale = new Sale();
sale.InvoiceNo = BillNo;
sale.Date = BillDate;
sale.Party = Customer;
sale.Amount = (decimal)TotalAmount;
dbContext.AddToSales(sale);
dbContext.SaveChanges();
This code add only the first row from StockList for all n times if there are n rows.
What wrongs with the code?
You are iterating over StockList, but you aren't actually using the iteration variable.
Everywhere that you use StockList[0], you should be using item.
Edit: Here is what your loop should look like:
foreach (StockItem item in StockList)
{
Master master = new Master();
master.VoucherNo = BillNo;
master.Voucher = "Sales";
master.StockName = item.StockName;
master.Quantity = item.Quantity;
master.Unit = item.Unit;
master.Price = item.UnitPrice;
master.Amount = item.Amount;
dbContext.AddToMasters(master);
dbContext.SaveChanges();
}

Categories

Resources