Populate dropdownlist with datareader from database - c#

Problem with populate specific dropdownlist values from database, i want to shows user all the current data from database tables to let them able to make changes, but i coulnd't shows the specific dropdownlist that user selected before. Im using linqdatasource to show all the dropdownlist value.
public partial class Update : System.Web.UI.Page
{
string cs = Global.CS;
DataClasses1DataContext db = new DataClasses1DataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) // only during initial load
{
string id = Request.QueryString["Item_ID"] ?? "";
string sql = "Select * FROM MenuItem WHERE Item_ID = #id";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Id", id);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
if ((string)dr["Category"] == "Breakfast" || (string)dr["Category"] == "Lunch" || (string)dr["Category"] == "Dinner")
{
DataBind();
lblId.Text = (string)dr["Item_ID"].ToString();
txtItemName.Text = (string)dr["ItemDesc"];
txtPrice.Text = (string)dr["Price"].ToString();
ddlCategory.Text = (string)dr["Category"];
//foreach (var checking in db.Sets)
//{
// string setID = checking.Set_ID.ToString();
// if (setID == (string)dr["Item_ID"])
// {
// ddlAlacarte.DataSourceID = "ldsAlacarte";
// **ddlAlacarte.DataTextField = (string)dr["ItemDesc"].ToString();
// ddlAlacarte.DataValueField = (string)dr["Item_ID"].ToString();**
// }
//}
}
else
{
ddlAlacarte.Enabled = false;
ddlBeverage.Enabled = false;
ddlSide.Enabled = false;
DataBind();
lblId.Text = (string)dr["Item_ID"].ToString();
txtItemName.Text = (string)dr["ItemDesc"];
txtPrice.Text = (string)dr["Price"].ToString();
ddlCategory.Text = (string)dr["Category"];
}
}
else
{
Response.Redirect("MenuAdmin.aspx");
}
DataBind();
dr.Close();
con.Close();
}
}
protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCategory.SelectedItem.Text == "Breakfast" || ddlCategory.SelectedItem.Text == "Lunch" || ddlCategory.SelectedItem.Text == "Dinner")
{
ddlAlacarte.Enabled = true;
ddlBeverage.Enabled = true;
ddlSide.Enabled = true;
DataBind();
}
else
{
ddlAlacarte.Enabled = false;
ddlBeverage.Enabled = false;
ddlSide.Enabled = false;
DataBind();
}
}
}

You need to add items in Dropdownlist while reading values.
Add the following code while you are reading values by using SqlDataReader.
while(dr.Read())
{
ListItem listItem = new ListItem();
listItem.Text = dr["Category"].ToString();
listItem.Value = dr["Category"].ToString();
categoryDropDownList.Items.Add(listItem);
}

I would use something like this
dropDownList.Items.Add(
new ListItem(){ Text = dr["Breakfast"], Value = dr["Breakfast"] }
);
and iterate through, populating the dropdown list. Is that what you want ?

Related

Handling multiple buttons in same asp.net page

hello everyone i am using two buttons on same asp.net webpage.both contain different codes
first button fetches the data from database here is the code
protected void Button1_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string checkaddress = "select address,city,zipcode from regforswa where username=" + username;
SqlCommand com = new SqlCommand(checkaddress, conn);
using (var reader = com.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["address"];
if (tmp != DBNull.Value)
{
laddress.Visible = true;
laddress.Text = reader["address"].ToString();
}
var cty = reader["city"];
if (cty != DBNull.Value)
{
lcity.Visible = true;
lcity.Text = reader["city"].ToString();
}
var zip = reader["zipcode"];
if (zip != DBNull.Value)
{
lzipcode.Visible = true;
lzipcode.Text = reader["zipcode"].ToString();
}
}
}
}
finally
{
conn.Close();
}
}
second button updates the value in the database using textbox values here is the code
protected void submit_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
string address=TextBox4.Text;
string city=TextBox5.Text;
string zipcode=TextBox6.Text;
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string updateaddress = "UPDATE regforswa SET address=#address,city=#city,zipcode=#zipcode WHERE username="+username;
SqlCommand com = new SqlCommand(updateaddress, conn);
com.Parameters.AddWithValue("#address",address);
com.Parameters.AddWithValue("#city",city);
com.Parameters.AddWithValue("#zipcode",zipcode);
// com.Parameters.AddWithValue("#username",username);
if (com.ExecuteNonQuery() == 1)
{
result.Visible = true;
result.Text = "congradulations.your address has been changed";
}
else
{
result.Visible = true;
result.Text = "sorry please try again";
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
}
}
but the problem is when i hit the first button the validation controls related to second button does not allow the page to be reloaded so i can not fetch the data.
my question is can we use two buttons on same webpage but with different functionality to perform?
I think you can use "Validation groups" to fix your problem. http://msdn.microsoft.com/en-us/library/ms227424(v=vs.100).aspx

No mapping exists from object type System.Data.DataRowView to a known managed provider native type

i have a windows form in c# which has 3 comboboxes. now the problem is when i pass the sql query of insertion it gives me this error. please help me to solve the error. here is the code.
namespace login
{
public partial class samplerequisition : Form
{
SqlConnection con = new SqlConnection("Data Source=TH07L019;Initial Catalog=procurement1;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader rdr;
DataSet dsreqname = new DataSet();
DataSet dsprepname = new DataSet();
DataSet dsauthorizedname = new DataSet();
public samplerequisition()
{
InitializeComponent();
}
bool IsAllValid()
{
if (String.IsNullOrEmpty(txtreqno.Text))
{
return false;
}
else if (String.IsNullOrEmpty(txtexpectedate.Text))
{
return false;
}
else if (String.IsNullOrEmpty(txtcc.Text))
{
return false;
}
else if (String.IsNullOrEmpty(txtbrand.Text))
{
return false;
}
/*else if (String.IsNullOrEmpty(txtprepname.Text))
{
return false;
}
else if (String.IsNullOrEmpty(txtauthorizedname.Text))
{
return false;
}*/
else if (cmbrequisitionname.SelectedItem==null)
{
return false;
}
else if (cmbpreparedname.SelectedItem == null)
{
return false;
}
else if (cmbauthorizedname.SelectedItem == null)
{
return false;
}
else if (Convert.ToString(dtreqdate.Value) == "")
{
return false;
}
else if (Convert.ToString(dtprepdate.Value) == "")
{
return false;
}
else if (Convert.ToString(dtauthorizedate.Value) == "")
{
return false;
}
else
{
return true;
}
}
private void samplerequisition_Load(object sender, EventArgs e)
{
SqlDataAdapter adp = new SqlDataAdapter(cmd);
cmd.Connection = con;
cmd.CommandText = "select * from employee";
adp.Fill(dsreqname,"employee");
cmbrequisitionname.DataSource = dsreqname.Tables["employee"];
cmbrequisitionname.DisplayMember = "fname";
cmbrequisitionname.SelectedIndex = -1;
adp.Fill(dsprepname, "employees");
cmbpreparedname.DataSource = dsprepname.Tables["employees"];
cmbpreparedname.DisplayMember = "fname";
cmbpreparedname.SelectedIndex = -1;
adp.Fill(dsauthorizedname, "employees");
cmbauthorizedname.DataSource = dsauthorizedname.Tables["employees"];
cmbauthorizedname.DisplayMember = "fname";
cmbauthorizedname.SelectedIndex = -1;
}
private void btnsave_Click(object sender, EventArgs e)
{
con.Open();
if (IsAllValid())
{
cmd.CommandText = "insert into samplerequisition(req_no,reqemployee_id,charges,expected_date,reqdate,costcenter_id,specific_brand,preparedemployee_id,prepared_date,authorizedemployee_id,auhtorized_date) values(#req_no,#reqemployee_id,#expected_date,#reqdate,#charges,#costcenter_id,#specific_brand,#preparedemployee_id,#prepared_date,#authorizedemployee_id,#auhtorized_date)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#req_no",txtreqno.Text);
cmd.Parameters.AddWithValue("#reqemployee_id",cmbrequisitionname.SelectedValue);
cmd.Parameters.AddWithValue("#expected_date",txtexpectedate.Text );
cmd.Parameters.AddWithValue("#reqdate", dtreqdate.Value);
cmd.Parameters.AddWithValue("#costcenter_id",txtcc.Text);
cmd.Parameters.AddWithValue("#specific_brand",txtbrand.Text);
cmd.Parameters.AddWithValue("#preparedemployee_id",cmbpreparedname.SelectedValue);
cmd.Parameters.AddWithValue("#prepared_date", dtprepdate.Value);
cmd.Parameters.AddWithValue("#authorizedemployee_id",cmbauthorizedname.SelectedValue);
cmd.Parameters.AddWithValue("#auhtorized_date", dtauthorizedate.Value);
if (rdcapex.Checked)
{
cmd.Parameters.AddWithValue("#charges", "Capex");
}
else
{
cmd.Parameters.AddWithValue("#charges", "revenue");
}
cmd.ExecuteNonQuery();
MessageBox.Show("record saved","requisition",MessageBoxButtons.OKCancel,MessageBoxIcon.Information);
}
else
{
MessageBox.Show("error","requisition",MessageBoxButtons.OKCancel,MessageBoxIcon.Error);
con.Close();
}
}
}
}
You are never setting what "value" to use for your combo boxes. So, by default, comboboxName.SelectedValue returns the whole row instead of just one column of the row. If you just want one column of the row (I am assuming fname like the displayed value) then just add the following 3 lines to your code.
cmbrequisitionname.ValueMember = "fname";
cmbpreparedname.ValueMember = "fname";
cmbauthorizedname.ValueMember = fname";

How to delete a row from gridview on button click after the row's checkbox is selected

I have a DataGridView created in C# windows forms and checkboxColumn added to it. The DataGridView is populated with other columns like Sno, AccountNo, Name, Salary (Sno is identitycolumn and primarykey).
I want to delete a row (using stored procedure) by selecting the checkbox and on button click which is out side DataGridView. Error at "FindControl".
Stored Procedure:
Create Procedure uspDeleteSelectedRow
As
Delete from EmpDetails where Sno=Sno
Go
private void btnDelete_Click(object sender, EventArgs e)
{
//Create String Collection to store IDs of
//records to be deleted
StringCollection idCollection = new StringCollection();
string strID = string.Empty;
//Loop through GridView rows to find checked rows
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)dataGridView1.Rows[i].
Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = dataGridView1.Rows[i].Cells[1].ToString();
idCollection.Add(strID);
}
}
}
if (idCollection.Count > 0)
{
//Call the method to Delete records
DeleteMultipleRecords(idCollection);
// rebind the GridView
dataGridView1.DataBind();
}
else
{
lblMessage.Text = "Please select any row to delete";
}
}
private void DeleteMultipleRecords(StringCollection idCollection)
{
//Create sql Connection and Sql Command
SqlConnection con = new SqlConnection(Helper.ConnectionString);
SqlCommand cmd = new SqlCommand();
string IDs = "";
foreach (string id in idCollection)
{
IDs += id.ToString() + ",";
}
try
{
string test = IDs.Substring
(0, IDs.LastIndexOf(","));
string sql = "Delete from EmpDetails" + " WHERE ID in (" + test + ")";
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string errorMsg = "Error in Deletion";
errorMsg += ex.Message;
throw new Exception(errorMsg);
}
finally
{
con.Close();
}
}
Let say this is your stored procedure:
ALTER PROCEDURE [dbo].[sp_ToDeleteEmpDetails] #Sno int
/*
(
#parameter1 int = 5,
#parameter2 datatype OUTPUT
)
*/
AS
DELETE FROM EmpDetails
WHERE Sno = Sno
RETURN
You don't need a StringCollection to delete or call the stored procedure.
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in dataGridView1.Rows)
{
bool IsBool = false;
if (bool.TryParse(item.Cells[1].EditedFormattedValue.ToString(), out IsBool)) //<--Where: The ColumnIndex of the DataGridViewCheckBoxCell
{
using (SqlConnection con = new SqlConnection(Helper.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("sp_ToDeleteEmpDetails", con))
{
try {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#sno", SqlDbType.Int).Value = item.Cells[0].EditedFormattedValue.ToString(); //<--Where: The ColumnIndex of the Primary key from your DataGridView
dataGridView1.Rows.RemoveAt(item.Cells[0].RowIndex);
con.Open();
cmd.ExecuteNonQuery();
} catch (Exception) {
throw;
}
finally
{
con.Close();
}
}
}
}
}
}
Please let me know if you have some encountered problem from my given answer.
Try this solution. In my code I have class and pass a list of it to gridview as my datasource.
//Class
public class User
{
public bool Selected { get; set; }
public string UserName { get; set; }
}
//Create a list and bind to the data grid view
private void Form1_Load(object sender, EventArgs e)
{
var users = new List<User> { new User { UserName = "Jobert", Selected = false }, new User { UserName = "John", Selected = true }, new User { UserName = "Leah", Selected = true }, new User { UserName = "Anna", Selected = false } };
dataGridView1.DataSource = users;
}
//On delete
private void btnDelete_Click(object sender, EventArgs e)
{
//get data back from the source
var source = dataGridView1.DataSource as List<User>;
var selectedItems = source.Where(x => x.Selected).ToList();
foreach (var item in selectedItems)
{
//perform the delete
}
}

ASP.NET checkbox incorrect value on postback

I am having an issue with some of my dynamic checkboxes on a project I am working on.
I have a tables, and in one cell per row, I have a checkbox. This checkbox is checked to "flag" that record. The records in the table are populated on a button click, after the user has set a series of filters. Therefore, the table contents completely change on each postback.
I use a list to preserve which records were already flagged, so that if a record appears that was previously checked, it will be checked on that retrieval too.
I am performing this check against my list in my page_load function and I can see through debugging that it is getting set correctly. However, when the page is done loading, the checked status is often wrong.
Do I need to move my checkbox state verification step to another part of the page lifecycle?
Any tips would be great. I found some questions on asp.net issues with checkboxes, but I they did not seem to be relevant to my issue.
Here is the code, feel free to critique any/all of it :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ScienceAssessmentToolASP
{
public partial class createnewtest : System.Web.UI.Page
{
private int n;
private SqlConnection conn = null;
private List<int> flaggedQuestions = new List<int>();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
var temp = (List<int>)Session["flaggedQuestions"];
if (temp != null)
flaggedQuestions = temp; ;//retrieve flags from session
try
{
GetConn();
ExecuteRetrieval();
n = 1;
}
catch (Exception ex) { n = 0; Response.Write("for debugging: " + ex); }
finally { if (conn != null) conn.Close(); }
if (n < 0)
//Label1.Text = "Connection Successful";
Label3.Text = "Failed to Connect to Database, please contact the administrator.";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
private void GetConn()
{
string connString = #"laalalala";
conn = new SqlConnection(connString);
conn.Open();
}
private void ExecuteRetrieval()
{
SqlDataReader reader = null;
string query;
if (!IsPostBack)
{
query = "select * from [ScienceQA]";
flaggedQuestions = (List<int>)Session["flaggedQuestions"];//retrieve flags from session
}
else query = "select * from [ScienceQA] where [GradeLevel] = " + DropDownList1.Text +
" and [Topic] = '" + DropDownList2.Text + "';";
SqlCommand cmd = new SqlCommand(query, conn);
reader = cmd.ExecuteReader();
TableHeaderRow headerRow = new TableHeaderRow();
TableHeaderCell idH = new TableHeaderCell();
TableHeaderCell questionH = new TableHeaderCell();
TableHeaderCell answerH = new TableHeaderCell();
TableHeaderCell flagH = new TableHeaderCell();
idH.Text = "ID";
questionH.Text = "Question";
answerH.Text = "Answer";
flagH.Text = "Flag";
headerRow.Cells.Add(idH);
headerRow.Cells.Add(questionH);
headerRow.Cells.Add(answerH);
headerRow.Cells.Add(flagH);
resultTable.Controls.Add(headerRow);
while (reader.Read())
{
TableRow row = new TableRow();
TableCell idCell = new TableCell();
TableCell qCell = new TableCell();
TableCell aCell = new TableCell();
TableCell flag = new TableCell();
idCell.Text = reader[0].ToString();
qCell.Text = reader[1].ToString();
aCell.Text = reader[2].ToString();
CheckBox flagBox = new CheckBox();
int id = Convert.ToInt32(idCell.Text);
flagBox.AutoPostBack = true;
flagBox.CheckedChanged += new System.EventHandler(flagButton_Click);
flagBox.EnableViewState = true;
flagBox.ViewStateMode = ViewStateMode.Enabled;
if (flaggedQuestions.Contains(id) && flagBox.ID == "flag" + id)
flagBox.Checked = true;
else flagBox.Checked = false;
flagBox.Text = id.ToString();
flag.Controls.Add(flagBox);
row.Cells.Add(idCell);
row.Cells.Add(qCell);
row.Cells.Add(aCell);
row.Cells.Add(flag);
resultTable.Controls.Add(row);
}
Label4.Visible = true;
flagCounter.Visible = true;
resultTable.Visible = true;
}
protected void flagButton_Click(object sender, EventArgs e)
{
CheckBox lb = (CheckBox)sender;
int questionID = Convert.ToInt32(lb.ID.Substring(4));
if (lb.Checked && !flaggedQuestions.Contains(questionID))
{
//lb.Checked = false;
flaggedQuestions.Add(questionID);
flagCounter.Text = Convert.ToString(flaggedQuestions.Count);
}
else
{
//lb.Checked = true;
flaggedQuestions.Remove(questionID);
flagCounter.Text = Convert.ToString(flaggedQuestions.Count);
}
Session["flaggedQuestions"] = flaggedQuestions;//store questions to session
}
protected void createTestButton_Click(object sender, EventArgs e)
{
//create a test
bool sendQuery = true;
string author = Session["user"].ToString();
string accessLevel = accessDropdown.Text;
int gradeLevel = Convert.ToInt32(DropDownList1.Text);
int questionCount = flaggedQuestions.Count();
string testType = testTypeDropDown.Text;
string description = descriptionBox.Text;
string questionString = "";
for (int i = 0; i < flaggedQuestions.Count(); i++)
questionString += flaggedQuestions[i] + ",";
string query = #"Insert into Tests Values ('" + author + "','" + questionString
+ "','" + accessLevel + "','" + gradeLevel + "','" + questionCount + "','"
+ testType + "','" + description +"');";
//check parameters
if (accessLevel == "")
{
errorLabel.Text = "Please choose an access level.";
sendQuery = false;
}
if (questionCount == 0)
{
errorLabel.Text = "Please flag a set of questions before creating a test.";
sendQuery = false;
}
if (testType == "")
{
errorLabel.Text = "Please choose a test type";
sendQuery = false;
}
if (description == "")
{
errorLabel.Text = "Please describe your test";
sendQuery = false;
}
if (sendQuery)
{
try
{
GetConn();
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Prepare();
int n;
n = cmd.ExecuteNonQuery();
}
catch (Exception e2) { n = 0; }
if (n == 1)
errorLabel.Text = "Test Created Successfully";
else errorLabel.Text = "Test Creation Failed, please check your parameters.";
}
}
}
}
Here was the solution that worked for me, moving the checkbox state check to the onprerender function.
protected override void OnPreRender(EventArgs e)
{
foreach (TableRow row in resultTable.Rows)
{
var cell = row.Cells[3];
foreach (Control control in cell.Controls)
{
var flagBox = control as CheckBox;
if (flagBox != null)
{
int id = Convert.ToInt32(flagBox.ID.Substring(4));
if (flaggedQuestions.Contains(id) && flagBox.ID == "flag" + id)
flagBox.Checked = true;
else flagBox.Checked = false;
}
}
}
}
You probably need to update the checked state of the checkboxes in PreRender as that occurs after the button click event has fired.

DataList keep displaying previously loaded datalist

I have a catalog function whereby user can filter their selection by clicking radiobutton. For example, by selecting the Dining radiobutton, all packages related to dining would appear.
And i using DataList1.Items.Count method to count the number search result. I had implement this method in the page_load, however the value of the number of datalist keep displaying previously loaded datalist.
Here is my code :
protected void Page_Load(object sender, EventArgs e)
{
DataList1.DataSourceID = "SqlDataSource3";
Label1.Text = DataList1.Items.Count.ToString();
}
private SqlDataReader getReader()
{
//get connection string from web.config
string strConnectionString = ConfigurationManager.ConnectionStrings["ASPNETDBConnectionString1"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT CategoryID, CatName from Category";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
//DataList1.DataSource = reader;
DataList1.DataBind();
// CommandBehavior.CloseConnection will automatically close connection
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataList1.DataSourceID = "SqlDataSource1";
if (RadioButtonList1.SelectedIndex == 0)
{
Session["catID"] = 1;
}
else if (RadioButtonList1.SelectedIndex == 1)
{
Session["catID"] = 2;
}
else if (RadioButtonList1.SelectedIndex == 2)
{
Session["catID"] = 3;
}
else if (RadioButtonList1.SelectedIndex == 3)
{
Session["catID"] = 4;
}
else if (RadioButtonList1.SelectedIndex == 4)
{
Session["catID"] = 5;
}
else
{
Session["catID"] = 8;
}
}
I had tried to place the Item.Count in other places of this code, but same problem persist..
Try this,
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DataList1.DataSourceID = "SqlDataSource3";
Label1.Text = DataList1.Items.Count.ToString();
}
}

Categories

Resources