What is the right way to populate a DropDownList from a database?
You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc).
For example, if you wanted to use a DataTable:
ddlSubject.DataSource = subjectsTable;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();
EDIT - More complete example
private void LoadSubjects()
{
DataTable subjects = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con);
adapter.Fill(subjects);
ddlSubject.DataSource = subjects;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();
}
catch (Exception ex)
{
// Handle the error
}
}
// Add the initial item - you can add this even if the options from the
// db were not successfully loaded
ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));
}
To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true:
<asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="<Select Subject>" Value="0" />
</asp:DropDownList>
You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove:
ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));
from the code-behind, or you'll have two "" items.
What is the way to populate a dropdownlist from a database in asp.net by using classes?
This line of code in your getNationality
method...
comm = new SqlCommand("spGetAllUsers", conn);
...should be this instead
comm = new SqlCommand("spGetNationalities", conn);
Databinding should work if your Nationality
table has columns ID and Nationality
How to populate HTML dropdown list with values from database
My guess is that you have a problem since you don't close your select-tag after the loop. Could that do the trick?
<select name="owner">
<?php
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"owner1\">" . $row['username'] . "</option>";
}
?>
</select>
New to MVC, Populating a DropDownList from a database
Finally figured it out. used ViewBag to populate the dropdown.
First add the database you need to your controller:
private MyDataBase db = new MyDataBase();
Then set a ViewBag as a new SelectList in the controller:
ViewBag.MyViewBagVariable = new SelectList(db.MyDataBaseModels, "ID", "ID");
And finally, under the View use the DropDownListFor helper with your ViewBag to populate the dropdown list:
@Html.DropDownListFor(model => model.MyDataBaseValue, (SelectList)ViewBag.MyViewBagVariable
How To Populate a DropDown List From a DataSet?
In order to show the data in the DropDownList control, you can use the following Code. To use the results of a Stored Procedure, you need to create the SELECT command:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim dt As New DataTable
Dim connString As String = "Server=MYCOMPUTER\SQLEXPRESS;Database=scales;Trusted_Connection=True"
Using myConn As New SqlConnection(connString)
myConn.Open()
Using cmd = myConn.CreateCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "dbo.uspMyStoredProc"
cmd.Parameters.AddWithValue("@MyInputParam", 123)
Using da As New SqlDataAdapter(cmd)
da.Fill(dt)
End Using
End Using
End Using
ComboBox1.DisplayMember = "scaleName"
ComboBox1.DataSource = dt
ComboBox1.DataBind()
End If
' ...
End Sub
I've adjusted the following things:
- Usually you only need to bind the data on the initial request. Therefore, the
if
statement at the beginning checks theIsPostBack
property. - In order to close and dispose the connection and the data datapter reliably, I've added some
using
statements. - In order to access the stored procedure, I've created a SqlCommand and set the
CommandType
toStoredProcedure
. TheCommandText
is set to the name of the Stored Procedure. In the sample, I've also added a parameter namedMyInputParam
that is sent to the Stored Procedure.
Populate DropDownList in ASP.NET MVC from database table using Entity Framework 6 and ViewModel
The main issue is that in the view you have new SelectList(Model.Grades, "ID", "Level")
but Grades
is IEnumerable<SelectListItem>
and SelectListItem
does not contain properties named ID
and Level
.
However there are a a few other issues with your code. First a view model should not contain a data model, and instead your view model should be
public class GradeSelectListViewModel
{
public int? ID { get; set; } // make this ID so you do not need an input for it
public string Name { get; set; }
.... // other properties of Employee that your editing
[Required(ErrorMessage = "..")]
public int? Level { get; set; } // make value types nullable to protect against under-posting attacks
public IEnumerable<SelectListItem> Grades { get; set; }
}
and add display and validation attributes as required. Note that I deleted the constructor (you don't seem to be using it, but if you did, then you also need to include a parameter-less constructor, otherwise an exception will be thrown when submitting to the POST method. I also assume that Level
should be typeof int
since you binding to the int ID
property of Grade
.
The the code in your GET method should be
Employee employee = db.Employees.Find(id);
var model = new GradeSelectListViewModel()
{
ID = employee.EmployeeID,
Name = employee.Name,
Level = employee.Level, // convert to int?
....
Grades = db.Grades.Select(x => new SelectListItem
{
Value = x.ID.ToString(),
Text = x.Level
})
};
return View(model);
and in the view
@Html.DropDownListFor(x => Model.Level, Model.Grades, "Select Level")
Note also that in the POST method, your need to reassign the SelectList
if you return the view because ModelState
is invalid.
How to populate a dropdown from database table using MVC?
Add the List to your model:
public List<string> DropDownList= new List<string>();
and then in your model create a function to load the data for the DropDownList from the database:
public void GetDropDownList()
{
//Pass your data base connection string here
using (SqlConnection c = new SqlConnection(cString))
//Pass your SQL Query and above created SqlConnection object "c"
using (SqlCommand cmd = new SqlCommand("SELECT Column1 FROM Table", c))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
DropDownList.Add(rdr["Column1"].ToString())
}
}
}
}
and then in Controller finally, you need to send your model to the view:
//Create object of your Model of controller
Model objModel = new Model();
//Call function to load the data for the DropDownList
objModel.GetDropDownList();
//return view with your object of model
return View(objModel);
Now in the Razor you can display this:
@Html.DropDownListFor(m => Model.DropDownList);
How to populate a html dropdown dynamically with values from a postgres database?
In the backend (flask) you can fetch all the values from the Postgres database using the query:
# code to connect to db
...
# code to fetch from database
list_of_regions = db.execute("select region_name from regions")
Then pass on those values to the front end page:
@app.route("/")
def index():
return render_template("index.html", list_of_regions = list_of_regions)
On the front end you can loop through the values with Jinja and add the items to the dropdown:
<label for="regions">Choose a region:</label>
<select name="regions" id="regions">
{% for region in list_of_regions %}
<option value={{region.lower()}}>{{region}}</option>
{% endfor %}
</select>
Just replace your case-specific code with the general code that is provided above and it should be good to go. I was not sure about how to connect to postgres database as I have worked mostly with MySQL, so I guess this package might help you out better for that.
Related Topics
Test If String Is a Guid Without Throwing Exceptions
Restrict Access to a Specific Controller by Ip Address in ASP.NET MVC Beta
What Does the Word "Literal" Mean
How to View Msil/Cil Generated by C# Compiler? Why Is It Called Assembly
Getting Http Status Code Number (200, 301, 404, etc.) from Httpwebrequest and Httpwebresponse
What .Net Collection Provides the Fastest Search
No Connection String Named 'Myentities' Could Be Found in the Application Config File
How to Read Values from the Querystring with ASP.NET Core
How to Get Values from Igrouping
Correct Way Communicate Wsse Usernametoken for Soap Webservice
Determine If Uploaded File Is Image (Any Format) on MVC
Why Do Local Variables Require Initialization, But Fields Do Not
Does Entity Framework Code First Support Stored Procedures
C# Open File with Default Application and Parameters
How to Check If Ienumerable Is Null or Empty
Fast Way to Convert a Two Dimensional Array to a List ( One Dimensional )