How do I create a picklist in ASP.NET/C#? - c#

All I want to do is a very simple select/picklist with values from a MySQL database.
I'm trying to find a simple solution online (I'm new to C#) and everything I'm finding is very complicated.
All I want to do is generate the <select><option.. etc parts, with all the attributes and values that I want to set.
This seems like it should be very, very easy. Can anyone give me some basic instructions, or point me to a tutorial that shows how to accomplish this?
Currently, I am using MySqlCommand and MySqlDataReader for classes to talk to the database (for another function).

Create a class for the entity you want to display. Ex : If you want to show all states in the dropdown, create State class
public class State
{
public int ID { set;get;}
public string Name { set;get;}
}
Now write a method in which you query the database and get the result to the DataReader, Iterate over the items and set the values a new object of our State class. Add each object to a list (of State class). So your method's return type will be a List of State class object.
public List<State> GetStates()
{
List<State> stateList=new List<State>();
// execute query, read from reader and add to the stateList
// the below code is SqlServer DB specific.
// you need to change the Connection,Command class for it to use with MySql.
using (var con= new SqlConnection("replace your connection string"))
{
string qry="SELECT ID,NAME FROM STATES";
var cmd= new SqlCommand(qry, objConnection);
cmd.CommandType = CommandType.Text;
con.Open();
using (var objReader = cmd.ExecuteReader())
{
if (objReader.HasRows)
{
while (objReader.Read())
{
var item=new State();
item.ID=reader.GetInt32(reader.GetOrdinal("ID"));
item.Name=reader.GetString(reader.GetOrdinal("Name"));
stateList.Add(item);
}
}
}
}
return stateList;
}
Now, have a DropDownList control in your page,
<asp:DropDownList id="states" runat="server" />
Now in the codebehind of this page, you can set the data for the dropdown( possibly in the Page_Load event)
if(!isPostBack)
{
states.DataSource=yourRepositary.GetStates();
states.DataTextField="Name";
states.DataValueField="ID";
states.DataBind();
}

I think what you searching for is something like a DropDownList, it accepts a DataSource, so you can use your already populated MySqlDataReader as it.
Something like this
MySqlDataReader dr = //the code to fill the MySqlDataReader
DropDownList1.DataSource = dr;
You can create the DropDownList in the design of your page.
To show the data you need to set then the values
DropDownList1.DataValueField = "DbField1";
DropDownList1.DataTextField = "DbField2";

Generally, in a list/drop down you got (a) the value that will be selected and (b) its presentation to the user. The first one might be some primary key, the second might be some label which is self-explaining to the user.
Assuming you got a table FOOD like
FoodValue | FoodLabel
---------------
00010 | Sausage
00020 | Eggs
00030 | Cheese
Put a listbox in your ASP.NET view, e.g. listBox1, then
you can read it in the code behind using
MySqlConnection con = new MySqlConnection("YOUR CONNECTION STRING");
MySqlCommand cmd = new MySqlCommand("SELECT FoodValue, FoodLabel FROM FOOD", con);
con.Open();
MySqlDataReader r = cmd.ExecuteReader();
while(r.Read()) {
listBox1.Items.Add(new ListItem(r["FoodLabel"], r["FoodValue"]);
}
con.Close();
But keep in mind this is a quick and dirty approach. In production code, you will need some separation of the presentation and data layer. Use the data source controls to bind your data in a better way.

Related

How to load the datagridview using OOP C#

I am a beginner at C# and .NET oop concepts. I want to load the datagridview. I don't know how to pass the data. What I tried so far I attached below.
I created a class std
public void get()
{
SqlConnection con = new SqlConnection("server =.; initial catalog=testdb; User ID=sa; Password=123");
string sql = "select * from std";
con.Open();
SqlCommand cm = new SqlCommand(sql, con);
SqlDataReader dr = cm.ExecuteReader();
while ( dr.Read())
{
string stname = dr["st_name"].ToString();
string nicnum = dr["nic"].ToString();
}
con.Close();
}
Form: I am getting data like this way
std ss = new std();
ss.get();
dataGridView1.Rows.Clear();
If I wrote like this way how to pass data into the datagridview columns? I am stuck in this area
It's easier like this:
public void FillGrid()
{
var dt = new DataTable();
var da = new SqlDataAdapter("select * from std", "server =.; initial catalog=testdb; User ID=sa; Password=123");
da.Fill(dt);
dataGridView1.DataSource = dt;
}
but if you're going to use such a low level method of database access you should consider adding a DataSet type of file to your project; visual studio will write all this code and more for you with a few mouse clicks, and it makes a good job of creating tables and adapters that are a lot easier to work with
you have made multiple mistakes. First you read data wirh dataraeader and in every iteration define two stname and nimnum variables like. So when loop ends variables are destroyed. You have to define data table and read data by dataraeader and and add them to it row by row. Or read by sqldataadapter and read it immediately and pass to datatable object.Finnaly you pass datatable as return object of function. Use this vala as datasource of datagridview property if I'm not wrong.

Void method is not running automatically when my project runs

i want to run my void method automatically when my project runs but it doesn't. i tried this but i think this is not good way. what is another way or how i can initialize my void method.
string fAccount;
[Key]
[Size(150)]
public string Account
{
get { GroupedAccount(); return fAccount; }
set { SetPropertyValue<string>(nameof(Account), ref fAccount, value); }
}
private void GroupedAccount()
{
SqlConnection conn = new SqlConnection("Connection");
SqlCommand cmd = new SqlCommand("SELECT * FROM Traders", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Open();
var groupedData = from b in dt.AsEnumerable()
group b by b.Field<string>("Account Name") into g
select new
{
fAccounts = g.Key,
};
foreach (var r in groupedData)
{
SqlCommand cmd2 = new SqlCommand("INSERT INTO dbo.TradersAccount (Account) VALUES (#Account)", conn);
cmd2.Parameters.AddWithValue("#Account", r.fAccounts);
cmd2.ExecuteNonQuery();
}
conn.Close();
}
In an XAF application, you have several places to put startup code, but in your case it looks like you are trying to initialize some objects in the database based on some existing data. The recommended place for this is the ModuleUpdater in the Updater.cs file. See the documentation for more information:
Create and update the application's database
Supply Initial Data for XPO.
Your Account property is part of an XPO object. XPO is an object relational mapper, that is, it abstracts away the complexities of transferring your C# classes to SQL storage. In general you should refrain from putting any additional code in the getters and setters of persisted properties. The DevExpress documentation is good:
Ways to add a business class
Comprehensive XAF Tutorial.
XPO best practices
In particular, XPO is intended to dispense with the need for direct SQL. If you need TradersAccount objects to be created or updated whenever an Trader object is modified, then you would normally create a TraderAccount XPO object and define an association property and create it with new TraderAccount(Session) and add it to the association property collection. Then XPO will automatically generate all of the corresponding SQL for you.

Pulling in Access Database Entry using C#

I'm trying to figure out how to pull specific Entry lines from an Access Database and into a C# Program.
I'm working with a friend to make a sudoku game. We want to pull different levels of difficulty of puzzles from an access database and into a C# program.
Now my question is: Is there a way to have to program pull the specific lines from the database or would we need to load them all into the program and then have them selected from there? These would be put into a two-dimensional array.
What would be the best way to go about this?
I'm not sure what soduku is, but I'm thinking that you need to query your Access DB. Something like this should get you started.
Class BusLogic
{
public List<string> ListboxItems = new List<string>();
public void PopulateListBoxItems(string userName)
{
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\redgabanan\Desktop\Gabanan_Red_dbaseCon\Red_Database.accdb";
using (OleDbConnection connection = new OleDbConnection(connString))
{
connection.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT * from Users WHERE LastName='#1'", connection);
command.Parameters.AddWithValue("#1", userName)
reader = command.ExecuteReader();
while (reader.Read())
{
ListboxItems.Add(reader[1].ToString()+","+reader[2].ToString());
}
}
}
}
You could use a DataReader as well.
http://www.akadia.com/services/dotnet_data_reader.html
You definitely don't want to pull in all data from a Table; you need to somehow Query the data set.

Place sql method in seperate class and return multiple strings

I have code that executes on a button click.
It connects to a sql database and reads two values.
All I want to achieve is to place this code in a separate class called 'DataManager' and then from my button click call a method in this class and get the two strings into my textboxes.
string sReference = txtReference.Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_SELECT_CONSHEAD_BY_ENQUIRY_NUMBER";
cmd.Parameters.AddWithValue("#EnquiryNumber", sReference);
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
txtAccount.Text = sdr["Consignee"].ToString();
txtAccount_Printed.Text = sdr["Consignee_Printed"].ToString();
}
con.Close();
con.Dispose();
I was thinking my method should look something like this
// Select from ConsHead by Reference Number
public string SelectConsHead(string sReference, out string sAccount, out string sAccount_Printed)
{
sAccount_Printed = "";
sAccount = "";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_SELECT_CONSHEAD_BY_ENQUIRY_NUMBER";
cmd.Parameters.AddWithValue("#EnquiryNumber", sReference);
// Attach connection to command
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
sAccount = sdr["Consignee"].ToString();
sAccount_Printed = sdr["Consignee_Printed"].ToString();
}
con.Close();
con.Dispose();
return sAccount + sAccount_Printed;
}
but I'm not sure on how to call the method and retrieve the corresponding values into the textboxes.
You ought to avoid the use of out parameters in your method definition. They are not being used as you are returning a concatenation of the account and account_printed strings anyway, so your method signature should look like this:
public string SelectConsHead(string sReference)
...and therefore you need to declare your local string variables, e.g:
var sAccount_Printed = "";
var sAccount = "";
You should also consider why you are prefixing string variable names with 's', as this is considered by many to be bad practice. For Microsoft's coding guidelines, see this link:
http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx
If your class is called DataManager, you need to instantiate the class in order to call your method (as it is not static). For example:
var sReference = // some code here to get sReference.
var dm = new DataManager();
var consHead = dm.SelectConsHead(sReference);
Another good practice is to favour the 'using' statement over manually opening and closing a SqlConnection. See here:
The C# using statement, SQL, and SqlConnection
In order to print the result in a textbox, assuming you are building a windows forms application, you need to know the id of the textbox, and then you can populate it like this (here the id of the textbox is 'myTextBox'):
myTextBox.Text = consHead;
The answer will vary based on whether you're working with a ASP.NET web app or a Windows forms application.
I can answer based on ASP.NET.
First, either your SelectConsHead method in your DataManager class will need to be static or you will need to create a new instance of your DataManager class in the code-behind of the page with your button and text boxes. If you go the static route, your method heading will look like this:
public static string SelectConsHead
Then in the code-behind of the page with your button and text boxes you will call the SelectConsHead method in the click event handler of your button.
If you go the non-static route, here is how you would instatiate your class and call its method in the codebehind:
DataManager dm = new DataManager();
dm.SelectConsHead(your parameters here);
Also, you should take Ronnie's advice in revising your method.

It don't get any data from DataReader

i work with N tiers tec in C# for ado, trying to make it easy to use and capable to change any database kind with out write all the cod all over again ,
my code here doesn't get any error but it doesn't get any values to my textbox
(i am trying to get data from table to many textboxs to update it later)
and here how code works:{
at first i make some functions to take any set any kind of parameters or set any command and then i make other function to to execute what ever i set or get from database all that Function i build it in folder name (Data Access Layer)
then i made other folder (Data Build layer)to take use all those function for what ever i want to do in any page (insert , update , delete , Select),
the last think i do it to call the function i made at at (Data Build layer) to my page or control ,
i do all that because if i Change the database Type ,i change only one class and other classes still the same
i hope i explain enough (sorry for my English not good enough)}
Code :
Class DataAccessLayer
public static void Setcommand (SqlCommand cmd,CommandType type,string commandtext)
{
cmd.CommandType=type;
cmd.CommandText=commandtext;
}
public static void AddSQLparameter(SqlCommand cmd, int size,SqlDbType type,object value,string paramName,ParameterDirection direction)
{
if (cmd == null)
{
throw (new ArgumentException("cmd"));
}
if (paramName == null)
{
throw (new ArgumentException("paramName"));
}
SqlParameter param=new SqlParameter();
param.ParameterName= paramName;
param.SqlDbType=type;
param.Size=size;
param.Value=value;
param.Direction=direction;
cmd.Parameters.Add(param);
}
public static SqlDataReader ExecuteSelectCommand(SqlCommand cmd)
{
if (cmd == null)
{
throw (new ArgumentNullException("cmd"));
}
SqlConnection con = new SqlConnection();
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
con.Close();
return dr ;
}
Class DatabuildLayer
SqlCommand com;
public DatabuildLayer()
{
com = new SqlCommand();
//
// TODO: Add constructor logic here
//
}
public SqlDataReader SelectCatalog(int catid)
{
DataAccessLayer.Setcommand(com, CommandType.Text, "select catname,catdescription,photo from category where catid=#catid" );
DataAccessLayer.addSQLparameter(com,16,SqlDbType.Int,catid,"#catid",ParameterDirection.Input);
return DataAccessLayer.ExecuteSelectCommand(com);;
}
and here my last code that retrieve my data to some textbox
in my Pageload :
protected void Page_Load(object sender, EventArgs e)
{
DatabuildLayer= new DatabuildLayer();
SqlDataReader dr ;
dr = obj.SelectCatalog(catselectddl.SelectedIndex);
if (dr.Read())
{
catnametxt.Text = dr["catname"].ToString();
catdestxt.Text = dr["catdescription"].ToString();
}
}
Is it possible that the query is returning nothing, and dr.Read() is returning false? Assuming the code actually executes (it is hard to tell from here) that is probably the only thing that would stop it working - either that or empty columns.
For what it is worth I think that your code needs to be tidied up a bit from a structural and conventions point of view. You should probably look through your code and consider the naming guidelines for the .NET framework. When others read your code they will want it formatted and consistent with this documentation. http://msdn.microsoft.com/en-us/library/xzf533w0(v=vs.71).aspx
Further, most people doing ASP.NET these days try to look for some way to inject external dependencies (such as databases) into their code using a framework like WebFormsMVP available at
http://webformsmvp.com/ in conjunction with an IoC container like autofac available at http://code.google.com/p/autofac/.
Using this approach you can push all external dependencies out of your application behind interfaces which would make it fairly trivial to plug in a different database engine.
Your current wrapper code is not doing anything particularly useful (just subsituting the existing methods or your own tht do the same thing), and it is not closing the connections correctly. It is... a bit of a mess.
If you aren't already massively familiar with the raw ADO.NET interfaces, then maybe consider something like "dapper" which will do all this for you, with a sane API:
short catid = 16;
using(var conn = GetOpenConnection()) {
var row = conn.Query(
"select catname,catdescription,photo from category where catid=#catid",
new { catid }).FirstOrDefault();
if(row != null) {
string name = row.catname, desc = row.catdescription;
// ...
}
}
Or if you have a class with CatName / CatDescription properties:
var obj = conn.Query<Catalogue>(
"select catname,catdescription,photo from category where catid=#catid",
new { catid }).FirstOrDefault();
from my experience, when you close a connection associated with a DataReader, nothing can be retrieved from the reader anymore.
//You closed the connection before returning the dr in the your method below:
public static SqlDataReader ExecuteSelectCommand(SqlCommand cmd)
{
if (cmd == null)
{
throw (new ArgumentNullException("cmd"));
}
SqlConnection con = new SqlConnection();
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
con.Close(); //here your connection was already closed
return dr ; //this dr is disconnected
}

Categories