There are 2 columns, one with name and the other with email addresses. I want to be able to display the names from the name's column in a dropdown but user the email in the next column when the form is submitted on my asp page.
public void FillAssignedToDropdownOnsite()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["onsite_db"].ConnectionString);
string query = "SELECT Name, EmailAddress FROM OnsiteData ";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
cmd.Connection.Open();
adpt.Fill(dt);
cmd.Connection.Close();
lstAssignedTo.DataSource = dt;
lstAssignedTo.DataTextField = "Name";
lstAssignedTo.DataBind();
lstAssignedTo.Items.Insert(0, "Select Onsite Tech");
}
Sql table is OnsiteData
columns are name and emailaddress
Form has a dropdown that sends an email.
It seems that your tag is misplaced. Supposing that this is ASP.NET instead of ASP-Classic and lstAssignedTo is a DropDownList I suggest to use the DataValueField set to EmailAddress
lstAssignedTo.DataSource = dt;
lstAssignedTo.DataTextField = "Name";
lstAssignedTo.DataValueField = "EMailAddress";
lstAssignedTo.DataBind();
when needed you could extract the email address for the selected user reading the Value property
if(lstAssignedTo.SelectedValue != null)
{
string email = lstAssignedTo.SelectedValue.ToString();
......
}
Not sure it's what you want :
lstAssignedTo.DataSource = dt;
lstAssignedTo.DataTextField = "Name";
lstAssignedTo.DataValueField = "EmailAddress"
lstAssignedTo.DataBind();
lstAssignedTo.Items.Insert(0, "Select Onsite Tech");
Like this the name is displayed and you can get the corresponding email with
var value = lstAssignedTo.SelectedValue;
Related
I have created a search function that returns product data in a DataGridView (data is coming from local database), it does work but I need to have control over returned data in my grid view.
Current behavior
It returns all columns of database row in DataGridView
What I want
Returning only 2 or 3 columns of searched item instead of all columns
Create new list of searched items so I can edit those returned data
Logic
Search for product
Get product name and price from database, add custom quantity field make new list and add this item to show in DataGridView
Be able to change quantity field in DataGridView
Code
Here is my search code that returns all columns of product table
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnectionString"].ConnectionString))
{
if (cn.State == ConnectionState.Closed)
cn.Open();
using (DataTable dt = new DataTable("Products"))
{
using (SqlCommand cmd = new SqlCommand("select * from Products where Id=#Id or Name like #Name", cn))
{
cmd.Parameters.AddWithValue("Id", searchBox.Text);
cmd.Parameters.AddWithValue("Name", string.Format("%{0}%", searchBox.Text));
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
// Following line will show all columns of founded product and replace it with next search result
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
selectedItems.DataSource = dt;
}
}
}
PS: Code above finds products based on id or name entered in search field and return all columns of product row.
Idea:
I think I can be able to create my list after finding product but the issue I'm facing is that I'm not sure how to get those specific columns from my dt (table row),
Here is what I've tried and failed (commented)
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnectionString"].ConnectionString))
{
if (cn.State == ConnectionState.Closed)
cn.Open();
using (DataTable dt = new DataTable("Products"))
{
using (SqlCommand cmd = new SqlCommand("select * from Products where Id=#Id or Name like #Name", cn))
{
cmd.Parameters.AddWithValue("Id", searchBox.Text);
cmd.Parameters.AddWithValue("Name", string.Format("%{0}%", searchBox.Text));
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
//selectedItems.DataSource = dt; //<-- changed with lines below
List<string> items = new List<string>();
items.Add(dt); // <-- here is the issue (it expect to get string of my table row let say: Price column, but I don't know how to get Price column value from dt)
selectedItems.DataSource = items;
}
}
}
PS: code above is just idea and obviously I am not sure if it is best way to do it or not that's why I'm asking here :)
Any suggestions?
Update
I've created new class and added my data to that class as following
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Price { get; set; }
public string Qty { get; set; }
}
Then in my query I added
List<Item> itemList = new List<Item>();
for (int i = 0; i < dt.Rows.Count; i++)
{
Item item = new Item();
item.Id = Convert.ToInt32(dt.Rows[i]["Id"]);
item.Name = dt.Rows[i]["Name"].ToString();
item.Price = dt.Rows[i]["SellPrice"].ToString();
item.Qty = dt.Rows[i]["Qty"].ToString();
itemList.Add(item);
}
selectedItems.DataSource = itemList;
Now it does return data in my selectedItems but when I search for next product instead of adding it to the list it replace it with first product.
According to your sql query you are selecting all columns of the table.
To get the specific columns please change your sql query as such:
SqlCommand cmd = new SqlCommand("select Products.id, Products.name from Products where Id=#Id or Name like #Name", cn);
Thank you.
As per my understanding based on the comments, you are looking for some Linq code.
You only need to convert your result to a list that you could use.
Here is some code that might help you achieve this.
var result = dt.AsEnumerable().Select(x=> new {
Id = x["Id"],
Name = x["Name"],
Quantity = {Your Logic here}
});
selectedItems.DataSource = result;
You can then assign result to your datasource. You did not specify what your datasource is assigned to (selectedItems) so I do not know what type it is. but this should theoretically work. Just remove Quantity = {Your Logic here} from the code and see if it display's after which you could then just add it back and populate what you want Quantity to be
UPDATE
Because selectedItems is a DataGridView it requires a DataTable object to display the data. In which case you can not use an anonymous list as I created you would need something like this.
DataTable dtResult = new DataTable();
dtResult.Columns.Add("Id");
dtResult.Columns.Add("Name");
dtResult.Columns.Add("Quantity");
var result = dt.AsEnumerable().Select(x=> dtResult.Rows.Add(x["Id"],
x["Name"],
{Your Logic for Quantity here}
));
selectedItems.DataSource = result;
If you want to test this solution you can create a console application in c# and do something like where you can see the datasource is correct.
You could refer to the following code to show specific column data from database in winform datagirdview.
private void button1_Click(object sender, EventArgs e)
{
string str = "str";
SqlConnection connection = new SqlConnection(str);
connection.Open();
string sql = "select * from Product where Id=#Id or Name like #Name";
SqlCommand command = new SqlCommand(sql,connection);
command.Parameters.AddWithValue("#Id", textBox1.Text);
command.Parameters.AddWithValue("#Name", string.Format("%{0}%", textBox1.Text));
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable table = new DataTable();
adapter.Fill(table);
var dt = from t in table.AsEnumerable()
select new
{
//Name=t.Field<string>("Name"), //The same way to show other columns data
Price = t.Field<string>("Price")
};
dataGridView1.DataSource = dt.ToList();
}
Result:
Database:
I am using a list box for the selection of file names pulled from SQL. The drop down works fine but is there a way I can bind a description also? The thought is to have the file name and description in the drop down list side by side. The file description is also a column in the same table.
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
layouts.DataSource = cmd.ExecuteReader();
layouts.DataTextField = "TextColumn";
layouts.DataValueField = "id";
layouts.DataBind();
con.Close();
This a example to bind bind two columns of data to a dropdown. Try it
using (SqlCommand cmd = new SqlCommand("select * from test1", con))
{
DataTable dt = new DataTable();
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(dt);
Dictionary<int,> lst = new Dictionary<int,>();
foreach (DataRow row in dt.Rows)
{
//Add values to Dictionary
string val = row[1].ToString() + " , " + row[2].ToString() + " , " + row[3].ToString();
lst.Add(Convert.ToInt32(row[0]), val);
}
DropDownList1.DataSource = lst;
DropDownList1.DataTextField = "Value";
DropDownList1.DataValueField = "Key";
DropDownList1.DataBind();
}
You can add an additional property (for example, NameDescription) to your model and use it:
public class File
{
public string Name { get; set; } // this is your file name property
public string Description { get; set; } // this is your description property
public string NameDescription => string.Format("{0} {1}", Name, Description); // the new property which contains name and description
}
I want to grab data from database and display in labels based on what the user selects in the list view.
I'm going off an example that does this with two list views, but I don't know how to do it when I'm sending data to a label.
This is the list view example I'm using (my label code is below this)
private void PopulateRecipeIngredients()
{
string query = "SELECT a.Name FROM Ingredient a " +
"INNER JOIN RecipeIngredient b ON a.Id = b.IngredientId " +
"WHERE b.RecipeId = #RecipeId";
// # is a parameter
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
// whatever recipe is selected in lstRecipes box, get the id of that and pass into query above
command.Parameters.AddWithValue("#RecipeId", lstRecipes.SelectedValue);
// DataTable holds the data return from query
DataTable ingredientTable = new DataTable();
// SqlDataAdapter object adapter fills the ingredientTable DataTable object with results from query
adapter.Fill(ingredientTable);
// Display value of Name ex. salad
lstIngredients.DisplayMember = "Name";
// Id column is how we reference
lstIngredients.ValueMember = "Id";
// connect list box on form to data in recipeTable
lstIngredients.DataSource = ingredientTable;
}
}
MY CODE:
private void PopulateCourseDetails()
{
string query = "SELECT * FROM Course_Info WHERE Id = #CourseId";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
command.Parameters.AddWithValue("#CourseId", lstCourses.SelectedValue);
DataTable courseTable = new DataTable();
adapter.Fill(courseTable);
lblCourseId.Text = "Course_id";
lblCourseSection.Text = "Course_section";
lblCourseName.Text = "Course_name";
lblCourseDay.Text = "Course_day";
lblCourseStartTime.Text = "Course_start_time";
lblCourseEndTime.Text = "Course_end_time";
lblCourseProfessor.Text = "Course_professor";
lblCourseProfessorEmail.Text = "Course_professor_email";
lstCourses.ValueMember = "Id";
}
}
lblCourseId.Text = (string)courseTable.Rows[0]["Course_id"]
should work as long as you have one row in the result table
Assuming that your DataTable has now been properly populated, you now have a table with a number of rows.
First you need to pull out the first row
var row = courseTable.Rows.FirstOrDefault();
Now you've got a row with a number of columns. You can access each column by either index or column name.
lblCourseId.Text = row[0];
If you want the label to maintain it's header, you can do something like
lblCourseId.Text = "Course_id: " + row[0];
I'm trying to get all the data from a column in the database. I found how to read the data from a specific column, but it shows only the first value.
Here's some of my code. Any idea how to read and show the rest data from the column?
public partial class main : Form
{
//Connect database
String connectionstring;
SqlConnection connection;
public main()
{
InitializeComponent();
//Connect database
connectionstring = ConfigurationManager.ConnectionStrings["Internet_Recovery.Properties.Settings.customerConnectionString"].ConnectionString;
Run();
}
private void Run()
{
using (connection = new SqlConnection(connectionstring))
//Select ip values from IP_table
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT Ip FROM IP_table ", connection))
{
DataTable iptable = new DataTable();
//Read ip value and add it in the listbox1
adapter.Fill(iptable);
listBox1.DataSource = iptable;
listBox1.ValueMember = "Ip";
listBox1.DisplayMember = "Id";
String num;
num = listBox1.SelectedValue.ToString();
you can do it like this :
DataSet data = new DataSet();
String num;
using (SqlConnection connection = new SqlConnection(connectionstring))
{
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT Ip FROM IP_table", connection))
{
connection.Open();
adapter.Fill(data);
listBox1.DataSource = data.Tables[0];
listBox1.DisplayMember = "Ip";
}
}
num = listBox1.SelectedValue.ToString();
First, your data doesn't have and Id field which you're trying to bind the DisplayMember to. Change your query to
SELECT Id, Ip FROM IP_table
Also you seem to be swapping the DisplayMember and ValueMember. They should be:
listBox1.ValueMember = "Id";
listBox1.DisplayMember = "Ip";
This works and displays all data from the Ip column in the list. It seems that you want to display the data from the other columns too. The ListBox control is not the best for that and you should consider using a GridView control instead. However, sometimes we don't care to display the data in grid format and all we care about is displaying it as a concatenated string in each item (e.g. firstname + " " lastname). If that's your case, you can either concatenate the columns in the query or in the code. Let's say you have the following columns in your table:
Id (e.g. 1)
Ip (e.g. 111.111.111)
Location (e.g. Virginia)
Provider (e.g. AT&T)
And let's assume you want to display them like this 111.111.111 AT&T (Virginia), then you can change your query to:
SELECT Id, Ip + ' ' + Provider + ' (' + Location + ')' AS Description FROM IP_table
And now you can change your binding properties to:
listBox1.ValueMember = "Id";
listBox1.DisplayMember = "Description";
I am using multi column in combo box. So,I would like to display a database table like this photo.
I tried the below coding but I get only the table date without the table borders.
private void affich()
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
req = "select id_amort_fiscal+''+amort_fiscal as combined from amortissementFiscal;";
SqlCommand sql = new SqlCommand(req, connection);
dr = new SqlDataAdapter(req, connection);
dr.Fill(ds, "amortissementFiscal");
multiColumnComboBox1.DataSource = ds.Tables["amortissementFiscal"];
multiColumnComboBox1.DisplayMember="combined";
multiColumnComboBox1.ValueMember = "combined";
connection.Close();
return;
}
this is what I get as a result:
any Help please and thanks :D
Is this third party control?
Anyway your query is showing you are only picking 1 column. Try adding more columns in query.
private void affich()
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
// *******************
// See the new_column2, new_column3 in the below query, replace them
// with your own columns
// ********************
req = "select id_amort_fiscal+''+amort_fiscal as combined, new_column2, new_column3 from amortissementFiscal;";
SqlCommand sql = new SqlCommand(req, connection);
dr = new SqlDataAdapter(req, connection);
dr.Fill(ds, "amortissementFiscal");
multiColumnComboBox1.DataSource = ds.Tables["amortissementFiscal"];
multiColumnComboBox1.DisplayMember="combined";
multiColumnComboBox1.ValueMember = "combined";
connection.Close();
return;
}
Make sure you have assigned ColumnToDisplay property to your MultiColumnCombobox.
multiColumnComboBox1.ColumnsToDisplay = new String[] {"Combinded Fiscal", "First Name"};
This will bind your column data into particular column. To display the proper column header, I preferred to specify alias in your sql query and try to add more columns in your query.
req = "select (id_amort_fiscal+''+amort_fiscal) As [Combinded Fiscal], FName As [First Name] from amortissementFiscal;";