How to populate dropdown list with data from database - c#

I have a stored procedure that pulls data from a database and displays it in a text box; it displays for the textboxes but doesn't display for the dropdown list or textbox that has textmode of date.
I've removed the select value option as it was throwing error SelectedValue which is invalid because it does not exist in the list of items.\r\nParameter name: value"
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "PP_spSearchReturnCrate";
if (!string.IsNullOrEmpty(txtReceiptNo.Text.Trim()))
{
cmd.Parameters.Add("#receiptNo", SqlDbType.VarChar).Value = txtReceiptNo.Text.Trim();
}
cmd.Connection = sqlConn;
sqlConn.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
String DATE = Convert.ToDateTime(dt.Rows[0]["returnDte"]).ToString("MM/dd/yyyy");
txtReturnDte.Text = DATE;
txtReceipt.Text = dt.Rows[0]["receiptNo"].ToString(); //Where ColumnName is the Field from the DB that you want to display
//ddlCustomer0.Text= dt.Rows[0]["custName"].ToString();
ddlDriver.Text = dt.Rows[0]["driverName"].ToString();
ddlUnitId.Text = dt.Rows[0]["unitId"].ToString();
txtNumber.Text = dt.Rows[0]["qtyReturned"].ToString();
txtLocation.Text = dt.Rows[0]["custLocation"].ToString();
Panel1.Visible = true;
}
else
{
lblmsg.Text = "No Records Found";
Panel1.Visible = false;
btnEdit.Visible = false;
}
I want to be able to show the data from the database in a drop down list as well as the date in textbox

Create a ListItem first, then add it to the dropdown.
ListItem li = new ListItem(dt.Rows[0]["custName"].ToString());
ddlCustomer0.Items.Add(li);

Related

Datatable only has one row when it should have many c# (using MySQLDataAdapter) for datagrid view

I`m having a problem displaying some data on a datagrid view. I send data to MySQL on form2 and then its supposed to be displayed in a datagrid view in form1. The datagrid view is updating perfectly but it seems that the datatable is not getting populated with the full information. There are 2 rows of data that should be displayed. I get 2 empty rows in datagrid view.I checked the database and the information is there. Is it my query that isnt right?
What I need are all the rows that have temp_quote.quote_id in the quotes_idquotes column. Can you help me out? Here is the code:
public void RefreshGrid_parts()
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["shopmanagerConnectionString1"];
MySqlConnection con = new MySqlConnection(conSettings.ToString());
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from shopmanager.parts where quotes_idquotes = '" + temp_quote.quote_id + "';",con);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.AutoGenerateColumns = false;
dataGridView1.ColumnCount = 6;
dataGridView1.Columns[0].HeaderText = "# Assembly";
dataGridView1.Columns[0].DataPropertyName = "assemblies_assembly_id";
dataGridView1.Columns[1].HeaderText = "# Part";
dataGridView1.Columns[1].DataPropertyName = "part_number";
dataGridView1.Columns[2].HeaderText = "# Item";
dataGridView1.Columns[2].DataPropertyName = "items_items_id";
dataGridView1.Columns[3].HeaderText = "# Description";
dataGridView1.Columns[3].DataPropertyName = "part_description";
dataGridView1.Columns[4].HeaderText = "Drawing Revision";
dataGridView1.Columns[4].DataPropertyName = "drawing_rev";
dataGridView1.Columns[5].HeaderText = "Quantity";
dataGridView1.Columns[5].DataPropertyName = "quantity";
dataGridView1.DataSource = dt;
con.Close();
}
Here is your property example:
(yes its mssql but the logic is the same just change the types, I don't have the mysql lib at hand right know. i guess you'll figure it out.)
SqlClient.SqlCommand comand = new SqlClient.SqlCommand("Select * From ExampleTable Where Colum1 = $1");
comand.Parameters.Add(new SqlClient.SqlParameter("$1", "1234") { DbType = DbType.Int32 });
this will also parse the decimal string into the correct data type (int32)
Try to comment the lines that create the headers to test if your data will appear in the DataGrid. Also put the AutoGenerateColumns to true. If it does, check the DataPropertyName if it's exactly the names of the columns on your query.
public void RefreshGrid_parts()
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["shopmanagerConnectionString1"];
MySqlConnection con = new MySqlConnection(conSettings.ToString());
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from shopmanager.parts where quotes_idquotes = '" + temp_quote.quote_id + "';",con);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.AutoGenerateColumns = true;
//dataGridView1.ColumnCount = 6;
//dataGridView1.Columns[0].HeaderText = "# Assembly";
//dataGridView1.Columns[0].DataPropertyName = "assemblies_assembly_id";
//dataGridView1.Columns[1].HeaderText = "# Part";
//dataGridView1.Columns[1].DataPropertyName = "part_number";
//dataGridView1.Columns[2].HeaderText = "# Item";
//dataGridView1.Columns[2].DataPropertyName = "items_items_id";
//dataGridView1.Columns[3].HeaderText = "# Description";
//dataGridView1.Columns[3].DataPropertyName = "part_description";
//dataGridView1.Columns[4].HeaderText = "Drawing Revision";
//dataGridView1.Columns[4].DataPropertyName = "drawing_rev";
//dataGridView1.Columns[5].HeaderText = "Quantity";
//dataGridView1.Columns[5].DataPropertyName = "quantity";
dataGridView1.DataSource = dt;
con.Close();
}
maybe take Rodrigos suggestion and just let the control generate the columns.
if you want to only this six columns just change the query.
public void RefreshGrid_parts()
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["shopmanagerConnectionString1"];
MySqlConnection con = new MySqlConnection(conSettings.ToString());
con.Open();
MySqlCommand cmd = new MySqlCommand("select assemblies_assembly_id as '# Assembly', part_number as '# Part', items_items_id as '# Item', part_description as '# Description', drawing_rev as 'Drawing Revision', quantity as 'Quantity' from shopmanager.parts where quotes_idquotes = $1;",con);
cmd.Parameters.Add(new MySqlParameter("$1", temp_quote.quote_id) { DbType = DbType.Int32 });
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dt;
con.Close();
}
I feel like an idiot. The code is good. The problem was that the text color in the datagrid view was white in a white box so I could not see it. Sorry to have bothered you guys with this. 24 hours spent on a non-existing problem! Wow!

How do you get the Id of the item in CheckListBox

I have a checkListBox in my windows form application and binded with my database data with SQL. I populate a list of item according to what I select from my comboBox. If I select item 1 from my comboBox, it will display customers' name who is using this item. I want get customers' id according to what I check in my checkListBox.
Here is how I fill my comboBox
private void fill_comboBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
string query = "select itemId, itemName from item_detail";
SqlDataAdapter da = new SqlDataAdapter();
myConn.Open();
DataTable dt = new DataTable();
SqlCommand command = new SqlCommand(query, myConn);
SqlDataReader reader = command.ExecuteReader();
dt.Load(reader);
DataRow dr;
dr= dt.NewRow();
dr.ItemArray = new object[] { 0, "<----------Select an item-------> " };
dt.Rows.InsertAt(dr, 0);
itemComboBox.DataSource = dr;
itemComboBox.ValueMember = "itemId";
itemComboBox.DisplayMember = "itemName";
fill_customerCheckListBox();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is how I fill my checkListBox
private void fill_customerCheckListBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
myConn.Open();
DataSet myDataSet = new DataSet();
myDataSet.CaseSensitive = true;
string commandString = "select fullName from[customer_detail] as cd LEFT JOIN[item_customer] as ic ON ic.customerId= cd.customerI WHERE ic.itemId= '" + itemCombBox.SelectedValue + "' ";
myCommand = new SqlCommand();
myCommand.Connection = myConn;
myCommand.CommandText = commandString;
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
myDataAdapter.SelectCommand = myCommand;
myDataAdapter.TableMappings.Add("Table", "customer_detail");
myDataAdapter.Fill(myDataSet);
DataTable myDataTable = myDataSet.Tables[0];
customerCB.Items.Clear();
string s = "Select All Customer";
customer.Items.Add(s);
foreach (DataRow dataRow in myDataTable.Rows)
{
customerCB.Items.Add(dataRow["fullName"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have a praremter for loop that trying to loop through every checked item from my customerCB, but this isn't working. When I am in my debug mode, the code DataRow row = (itemChecked as DataRowView).Row; is causing an exception
Object reference is not set to an instance of an object.
I have no idea how to fix this. Help will be appreciated, thanks
string parameterList = "";
foreach (object itemChecked in customerCB.CheckedItems)
{
DataRow row = (itemChecked as DataRowView).Row;
parameterList += (parameterList.Length == 0) ? row[0].ToString() : ", " + row[0].ToString();
}
Try the Following way !!
foreach(object itemChecked in checkedListBox1.CheckedItems)
{
DataRowView castedItem = itemChecked as DataRowView;
string fullName= castedItem["fullName"];
}
(OR) You would need to cast or parse the items to their strongly typed equivalents, or use the System.Data.DataSetExtensions namespace to use the DataRowExtensions.Field method demonstrated below:
foreach (var item in checkedListBox1.CheckedItems)
{
var row = (itemChecked as DataRowView).Row;
int id = row.Field<int>("ID");
string name = row.Field<string>("fullName");
}
it seems than when you are populating your combobox your are entering dataRow["fullName"] therefore this cast DataRow row = (itemChecked as DataRowView).Row won't work as itemChecked only contains the value of fullName and not the row, try adding the dataRow instead.

how to update GridView row at once in sql database

I have DLL class to call the table
public DataTable GetTemTableValue(string TableName)
{
SqlConnection conn = new SqlConnection(sConnectionString);
conn.Open();
string query = "select * from " + TableName + "";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
DataTable ds = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
conn.Close();
return ds;
}
and i am binding the table to grid view
private void LoadData()
{
clsDataAccess objDAL = new clsDataAccess();
DataTable DS = new DataTable();
string objBLL = DDLTemTableList.SelectedValue.ToString();
DS = objDAL.GetTemTableValue(objBLL);
if (DS != null && DS.Rows.Count != 0)
{
lblNoRecord.Visible = false;
foreach (DataColumn col in DS.Columns)
{
//Declare the bound field and allocate memory for the bound field.
BoundField bfield = new BoundField();
//Initalize the DataField value.
bfield.DataField = col.ColumnName;
//Initialize the HeaderText field value.
bfield.HeaderText = col.ColumnName;
//Add the newly created bound field to the GridView.
GVDataEntry.Columns.Add(bfield);
}
GVDataEntry.DataSource = DS;
GVDataEntry.DataBind();
GVDataEntry.Visible = true;
}
else
{
lblNoRecord.Visible = true;
GVDataEntry.DataSource = null;
GVDataEntry.DataBind();
//GVDataEntry.EmptyDataText = "No recorddata found";
}
so Table is loading to Grid View. every time when i change the tables in dropdownbox and press search button columns will change dynamically so how can i update data in Grid view through using RowEditing,RowUpdating function and i need to store the date in database?

To Display controls based on the dropdownlist selected item?

For Dropdownlist items i have written the following code:
protected void dropdowndatasrc()
{
con = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
string command = "select eventname from Events";
cmd = new OleDbCommand(command);
dataadapter = new OleDbDataAdapter(command, con);
DataSet dataset = new DataSet();
con.Open();
DataTable dt = new DataTable("PayEvent");
dataadapter.Fill(dt);
DropDownList4.DataSource = dt;
DropDownList4.DataTextField = dt.Columns[0].ToString();
// DropDownList4.DataValueField = dt.Columns[0].ToString();
DropDownList4.DataBind();
}
I have to display controls based on the value of the dropdownlist (in the access database there is a column named payevent in that it has Yes/No datatype if the selected item in the database have 'yes' means display controls if not no controls must be displayed)
I have tried this code but not worked
protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox11.Text = DropDownList4.SelectedItem.Text;
con = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
string query = "select payevent from Events where eventname=#dropdownlist";
con.Open();
//string query="select payevent from Events";
cmd = new OleDbCommand(query, con);
cmd.Parameters.Add("#dropdownlist", selectedtext);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string value = reader.GetValue((0)).ToString();
TextBox11.Text = value.ToString();
if (value == "True" || value == "true")
{ pnl.Visible = false; }
else if (value == "False" || value == "false")
{ pnl.Visible = true; }
}
}
the table structure as follows:
**eventname payevent**
Work Shop Yes
emsisoft workshop Yes
ECE No
CSE No
Need help !!!
The usually issue is that you make databind on the dropdownlist again after the post back and the value is lost. So on page load, do not call the dropdowndatasrc on post back as:
if(!IsPostBack)
dropdowndatasrc();
same issue: Dropdown list not selecting value asp.net

Data does not display when making loop statement in datagridview control

I had datagridview control which retrieves data from database. I had my code to do that, but no data apeared in gridview. I made a break point in the loop but when on DataGridViewTextBoxCell Number = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l];
datagrid view apeared with no data
private void getcategory()
{
for (int i = 0; i < DGCategory.Rows.Count; i++)
{
for (int l = 0; l < DGCategory.Rows[i].Cells.Count; l++)
{
DataGridViewTextBoxCell Number = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l];
DataGridViewTextBoxCell Category = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l];
DataGridViewTextBoxCell Parent = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l];
DataGridViewCheckBoxCell Active = (DataGridViewCheckBoxCell)DGCategory.Rows[i].Cells[l];
DataGridViewTextBoxCell AddDate = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l];
using (SqlConnection Con = GetConnection())
{
SqlCommand cmd = new SqlCommand("SP_GetAllCategories", Con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.Read())
{
Number.Value = dr["Number"].ToString();
Category.Value = dr["Category"].ToString();
Parent.Value = dr["Parent"].ToString();
Active.Value = dr["Active"].ToString();
AddDate.Value = dr["AddDate"].ToString();
}
}
}
}
}
If u want to get values from your database into a grid view .. use the following:
write your query in a String called "selectCommand" for example then use a dataset to get the results:
public DataSet GetSearchEmpResults(string emp_fn)
{
string selectCommand = #"select
emp.first_name as 'First Name',
emp.last_name as 'Last Name'
from Employees emp
where emp.first_name = '" + emp_fn + "';";
SqlCommand command = new SqlCommand(selectCommand, this.Connection);
DataSet ds = new DataSet("Results");
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(ds, "Results");
return ds;
}
then in the data gridview code:
DataSet results = db.GetSearchEmpResults(fristName, lastName); //this depends on your results
dataGridViewResults.DataSource = results;
dataGridViewResults.DataMember = "Results";
the dataGridViewResults is the name of the data gridview you want your results yo appear in.
Note that you should provide the connection to your database in order to receive the results.

Categories