I dynamically create a RadioButtonList or a CheckBoxList depending on a condition within a Button_Click event (which works).
protected void btnGetQuestion_Click(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
MySqlDataReader reader;
List<string> listOfAnswerIDs = new List<string>();
List<string> listOfAnswers = new List<string>();
List<string> listOfCorrectAnswerIDs = new List<string>();
int questionCounter = 0;
//get questionIDs and store in ViewState["listOfQuestionIDs"]
getListOfQuestionIDs();
try
{
conn.Open();
string cmdText = "SELECT * FROM questions_m WHERE question_id=#QuestionID";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#QuestionID", MySqlDbType.Int32);
cmd.Parameters["#QuestionID"].Value = listOfQuestionIDs[questionCounter];
reader = cmd.ExecuteReader();
if (reader.Read())
{
lblQuestion.Text = reader["question"].ToString();
if (reader["type"].ToString().Equals("C"))
{
CheckBoxList cblAnswers = new CheckBoxList();
cblAnswers.ID = "cblAnswers";
Page.Form.Controls.Add(cblAnswers);
}
else if (reader["type"].ToString().Equals("R"))
{
RadioButtonList rblAnswers = new RadioButtonList();
rblAnswers.ID = "rblAnswers";
Page.Form.Controls.Add(rblAnswers);
}
questionCounter += 1;
ViewState["questionCounter"] = questionCounter;
ViewState["QuestionID"] = Convert.ToInt32(reader["question_id"]);
reader.Close();
string cmdText2 = "SELECT * FROM answers WHERE question_id=#QuestionID";
MySqlCommand cmdAnswers = new MySqlCommand(cmdText2, conn);
cmdAnswers.Parameters.Add("#QuestionID", MySqlDbType.Int32);
cmdAnswers.Parameters["#QuestionID"].Value = ViewState["QuestionID"];
reader = cmdAnswers.ExecuteReader();
while (reader.Read())
{
listOfAnswerIDs.Add(reader["answer_id"].ToString());
listOfAnswers.Add(reader["answer"].ToString());
}
reader.Close();
populateAnswers(listOfAnswers, listOfAnswerIDs);
}
reader.Close();
}
catch
{
lblError.Text = "Database connection error - failed to read records.";
}
finally
{
conn.Close();
}
}
I want to create a method that I can run in another button click event (btnNext_Click) that will remove the RadioButtonList or CheckBoxList if one exists.
I've tried the following but it doesn't seem to work:
protected void clearAnswers()
{
if (((CheckBoxList)this.FindControl("cblAnswers")) != null)
{
Page.Form.Controls.Remove(this.FindControl("cblAnswers"));
}
if (((RadioButtonList)this.FindControl("rblAnswers")) != null)
{
Page.Form.Controls.Remove(this.FindControl("rblAnswers"));
}
}
UPDATE:
I think the issue I had occured with the repopulation of the RadioButtonList/CheckBoxList. If I cleared each item before repopulating them, that resolved my problem.
if (((CheckBoxList)this.FindControl("cblAnswers")) != null)
{
((CheckBoxList)this.FindControl("cblAnswers")).Items.Clear();
foreach (int num in numbers)
{
((CheckBoxList)this.FindControl("cblAnswers")).Items.Add(ans[num - 1]);
}
}
if (((RadioButtonList)this.FindControl("rblAnswers")) != null)
{
((RadioButtonList)this.FindControl("rblAnswers")).Items.Clear();
foreach (int num in numbers)
{
((RadioButtonList)this.FindControl("rblAnswers")).Items.Add(ans[num - 1]);
}
}
Try this:
protected void clearAnswers()
{
CheckBoxList cblAnswers = (CheckBoxList)this.FindControl("cblAnswers");
RadioButtonList rblAnswers = (RadioButtonList)this.FindControl("rblAnswers");
if (cblAnswers != null)
{
Page.Form.Controls.Remove(cblAnswers);
}
if (rblAnswers != null)
{
Page.Form.Controls.Remove(rblAnswers);
}
}
Related
I'm trying to add some data from a SQLite database, inside a ListView.
I'm having some difficulties as I want to insert all the data of the column and not a single record.
TEST CODE:
Form1.cs {Load}
private void home_form_Load(object sender, EventArgs e)
{
listView1.Refresh();
listView1.View = View.Details;
listView1.Columns.Add("ID");
listView1.Columns.Add("Grado");
listView1.Columns.Add("Cognome");
listView1.Columns.Add("Nome");
listView1.Columns.Add("Status");
}
Form1.cs {menu_button_gestionepax}
private void menu_button_gestionepax_Click(object sender, EventArgs e)
{
menu_button_dashboard.BackColor = System.Drawing.Color.DeepSkyBlue;
panel_dashboard.Visible = false;
gestionepersonale_panel.Visible = true;
menu_button_gestionepax.BackColor = System.Drawing.Color.Blue;
listView1.Refresh();
ListViewItem lst = new ListViewItem();
lst.SubItems.Add(LoadUsers.ManagerFind());
lst.SubItems.Add(LoadUsers.ManagerFind());
lst.SubItems.Add(LoadUsers.ManagerFind());
lst.SubItems.Add(LoadUsers.ManagerFind());
lst.SubItems.Add(LoadUsers.ManagerFind());
listView1.Items.Add(lst);
/*
string[] row = { LoadUsers.ManagerFindid(), LoadUsers.ManagerFindid() };
var listViewItem = new ListViewItem(row);
infobox_listview.Items.Add(listViewItem);
*/
}
LoadUsers.cs
public dynamic string ManagerFind()
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var select = cnn.Query($"select id from utenti");
if (select.Any())
{ return select[0].ToString(); }
else return "wrong";
}
}
I have also done various other tests and one of the difficulties in some cases is to call string ManagerFind() from LoadUsers.cs
Try something like this to get your rows and columns from your sql i know this is how you do it in SQL im sure there is a similar way to do it with sqlLite
using (SqlConnection connection = new SqlConnection(_sqlConnectionStringFromUserImput))
{
connection.Open();
if (connection.State == ConnectionState.Open)
{
SqlCommand sqlCommand =
new SqlCommand(
"select id from utenti",
connection)
{
CommandType = CommandType.Text,
CommandTimeout = 20
};
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
DateTime datetimefield = reader.GetFieldValue<DateTime>(0);
string stringField = reader.GetFieldValue<string>(1);
}
}
reader.Close();
}
connection.Close();
}
I'm getting a list of datetimes and storing them in a checkboxlist with this bit of code:
<anthem:CheckBox ID="chkAll" runat="server" OnCheckedchanged="chkAll_CheckedChanged" Text="Select/Deselect All" AutoPostBack="true"
style="margin-left: 128px" >
</anthem:CheckBox>
<anthem:CheckBoxList ID="CheckOpenTimesheets" runat="server" OnSelectedIndexChanged="checkbox_Selected" AutoPostBack="true"
style="margin-left: 128px" >
</anthem:CheckBoxList>
Here's the relevant code behind:
List<ListItem> toBeRemoved = new List<ListItem>();
for (int i = 1; i < CheckOpenTimesheets.Items.Count; i++)
{
toBeRemoved.Add(CheckOpenTimesheets.Items[i]);
}
for (int i = 0; i < toBeRemoved.Count; i++)
{
CheckOpenTimesheets.Items.Remove(toBeRemoved[i]);
}
String sql = "SELECT StartDate FROM Periods WHERE User_ID = #userid AND (PeriodStatus_ID = 1 OR PeriodStatus_ID = 2) ORDER BY StartDate DESC";
command.CommandText = sql;
command.Parameters.Add(new SqlParameter("userid", ddlActingAs.SelectedValue.ToString()));
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
ListItem item = new ListItem();
item.Text += reader.GetDateTime(0).ToString("MM/dd/yyyy") + " is open";
item.Value = reader["StartDate"].ToString();
CheckOpenTimesheets.Items.Add(item);
}
CheckOpenTimesheets.UpdateAfterCallBack = true;
reader.Close();
//The functions below are for selecting/deselecting the items in the checklistbox
protected void chkAll_CheckedChanged(object sender, EventArgs e)
{
foreach (ListItem item in CheckOpenTimesheets.Items)
{
item.Selected = chkAll.Checked;
}
}
protected void checkbox_Selected(object sender, EventArgs e)
{
chkAll.CheckedChanged -= chkAll_CheckedChanged;
CheckBoxList checkOpenTimesheets = (CheckBoxList)sender;
if (allItemsCheckedInCheckBoxList(checkOpenTimesheets))
{
chkAll.Checked = true;
}
else if (allItemsUnCheckedInCheckBoxList(checkOpenTimesheets))
{
chkAll.Checked = false;
}
chkAll.CheckedChanged += chkAll_CheckedChanged;
}
private bool allItemsCheckedInCheckBoxList(CheckBoxList checkBoxList)
{
bool allItemsChecked = true;
foreach (ListItem item in checkBoxList.Items)
{
allItemsChecked = item.Selected;
if (!allItemsChecked)
break;
}
return allItemsChecked;
}
private bool allItemsUnCheckedInCheckBoxList(CheckBoxList checkBoxList)
{
bool allItemsUnChecked = false;
foreach (ListItem item in checkBoxList.Items)
{
allItemsUnChecked = item.Selected;
if (allItemsUnChecked)
break;
}
return allItemsUnChecked;
}
What I'm trying to do is, when a button I have on the page is clicked, it will loop through the checkboxlist, and every item that is checked, will update the PeriodStatus_ID to 5 for each of those items in the SQL table.
The function for the button click is here (not sure how to go about this):
protected void SubmitAll_Click(object sender, EventArgs e)
{
foreach (ListItem item in CheckOpenTimesheets.Items)
{
SqlCommand command = new SqlCommand();
command.Connection = gConn;
if (item.Selected == true)
{
String sql = "UPDATE Periods SET PeriodStatus_ID=5 WHERE User_ID = #userid AND StartDate = #startdate";
command.CommandText = sql;
command.Parameters.Add(new SqlParameter("userid", ddlActingAs.SelectedValue.ToString()));
command.Parameters.Add(new SqlParameter("startdate", item.Value));
}
}
}
Any ideas on achieving this would be great, thanks in advance.
You updated your code, so I updated mine, but I changed my mind about how you want to structure it. You've also left out the ExecuteNonQuery statement, which is the way to send an Update command.
protected void SubmitAll_Click(object sender, EventArgs e)
{
SqlCommand command = new SqlCommand();
command.Connection = gConn;
String sql = "UPDATE Periods SET PeriodStatus_ID=5 WHERE User_ID = #userid AND StartDate = #startdate";
command.CommandText = sql;
command.Parameters.Add("userid");
command.Parameters.Add("startdate");
for (int i = 0; i < CheckOpenTimesheets.Items.Count; i++)
{
if (item.Selected == true)
{
command.Parameters("userid").Value = ddlActingAs.SelectedValue.ToString();
command.Parameters("startdate").Value = item.Value;
command.ExecuteNonQuery();
}
}
}
I am getting this error
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
I read this question and it states that the exception is caused because of not closing the connection. However, i close all the connection in my code
This is my code, it is simple
public partial class index : System.Web.UI.Page
{
private static string defaultReason = "reason not selected";
protected override object SaveViewState()
{
//save view state right after the dynamic controlss added
var viewState = new object[1];
viewState[0] = base.SaveViewState();
return viewState;
}
protected override void LoadViewState(object savedState)
{
//load data frm saved viewstate
if (savedState is object[] && ((object[])savedState).Length == 1)
{
var viewState = (object[])savedState;
fillReasons();
base.LoadViewState(viewState[0]);
}
else
{
base.LoadViewState(savedState);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string callIDValue = Request.QueryString["CallID"];
string callerIDValue = Request.QueryString["CallerID"];
if (!String.IsNullOrEmpty(callerIDValue))
{
callerID.Value = callerIDValue;
if (!String.IsNullOrEmpty(callIDValue))
{
string query = "INSERT INTO Reason (callerID, callID, reason, timestamp) VALUES (#callerID, #callID, #reason, #timestamp)";
SqlConnection con = getConnection();
SqlCommand command = new SqlCommand(query, con);
command.Parameters.AddWithValue("#callerID", callerIDValue);
command.Parameters.AddWithValue("#callID", callIDValue);
command.Parameters.AddWithValue("#reason", defaultReason);
command.Parameters.AddWithValue("#timestamp", DateTime.Now.ToString());
try
{
con.Open();
command.ExecuteNonQuery();
command.Dispose();
con.Close();
}
catch (Exception ee)
{
command.Dispose();
con.Close();
message.InnerHtml = ee.Message;
}
}
else
{
message.InnerHtml = "Call ID is empty";
}
}
else
{
callerID.Value = "Undefined";
message.InnerHtml = "Caller ID is empty";
}
fillReasons();
}
else
{
}
}
private void fillReasons()
{
string query = "SELECT * FROM wrapuplist WHERE isEnabled = #isEnabled";
SqlConnection con = new SqlConnection(getConnectionString());
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("isEnabled", true);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable results = new DataTable();
da.Fill(results);
int numberOfReasons = 0; // a integer variable to know if the number of the reasons becomes able to be divided by four
HtmlGenericControl div = null;
foreach (DataRow row in results.Rows)
{
numberOfReasons++;
if ((numberOfReasons % 4) == 1)
{
div = new HtmlGenericControl("div");
div.Attributes.Add("class", "oneLine");
}
RadioButton radioButton = new RadioButton();
radioButton.ID = "reason_" + row["reasonName"].ToString();
radioButton.GroupName = "reason";
radioButton.Text = row["reasonName"].ToString();
div.Controls.Add(radioButton);
if (numberOfReasons % 4 == 0)
{
myValueDiv.Controls.Add(div);
//numberOfReasons = 0;
}
else if (numberOfReasons == results.Rows.Count)
{
myValueDiv.Controls.Add(div);
//numberOfReasons = 0;
}
}
cmd.Dispose();
da.Dispose();
con.Close();
}
private SqlConnection getConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["vmpcon"].ConnectionString);
}
private string getConnectionString()
{
return ConfigurationManager.ConnectionStrings["wrapupconnection"].ConnectionString.ToString();
}
protected void buttonSaveClose_Click(object sender, EventArgs e)
{
var divcontrols = myValueDiv.Controls.OfType<HtmlGenericControl>();
bool isFound = false;
RadioButton checkedRadioButton = null;
foreach (HtmlGenericControl loHTML in divcontrols)
{
var checkedRadioButtons = loHTML.Controls.OfType<RadioButton>().Where(radButton => radButton.Checked).ToList();
foreach (RadioButton lobtn in checkedRadioButtons)
{
if (lobtn.Checked)
{
isFound = true;
checkedRadioButton = lobtn;
}
}
}
if (isFound)
{
sReasonError.InnerText = "";
string reason = "";
reason = checkedRadioButton.Text;
string callIDValue = Request.QueryString["CallID"];
string callerIDValue = Request.QueryString["CallerID"];
if (String.IsNullOrEmpty(callIDValue))
{
message.InnerText = "Call ID is empty";
}
else if (String.IsNullOrEmpty(callerIDValue))
{
message.InnerText = "Caller ID is empty";
}
else
{
message.InnerText = "";
string query2 = "SELECT * FROM Reason WHERE callID = #callID AND reason != #reason";
SqlConnection con = getConnection();
SqlCommand command2 = new SqlCommand(query2, con);
command2.Parameters.AddWithValue("#callID", callIDValue);
command2.Parameters.AddWithValue("#reason", defaultReason);
con.Open();
if (command2.ExecuteScalar() != null)
{
message.InnerText = "Already saved";
command2.Dispose();
con.Close();
}
else
{
command2.Dispose();
con.Close();
string notes = taNotes.InnerText;
string query = "UPDATE Reason SET reason = #reason, notes = #notes, timestamp = #timestamp WHERE callID = #callID";
SqlCommand command = new SqlCommand(query, con);
command.Parameters.AddWithValue("#callID", callIDValue);
command.Parameters.AddWithValue("#reason", reason);
command.Parameters.AddWithValue("#notes", notes);
command.Parameters.AddWithValue("#timestamp", DateTime.Now.ToString());
try
{
con.Open();
command.ExecuteNonQuery();
command.Dispose();
con.Close();
message.InnerText = "Done Successfully";
//ClientScript.RegisterStartupScript(typeof(Page), "closePage", "<script type='text/JavaScript'>window.close();</script>");
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true);
}
catch (Exception ee)
{
command.Dispose();
con.Close();
message.InnerText = "Error, " + ee.Message;
}
}
}
}
else
{
sReasonError.InnerText = "Required";
message.InnerText = "Select a reason";
//fillReasons();
}
}
}
as you see, all the connection are being closed, what wrong did I do please?
Closing connections and disposing should be in a finally block while using a try catch.
or use a using block like the one below
using(SqlConnection con = getConnection())
{
con.Open();
//Do your operation here. The connection will be closed and disposed automatically when the using scope is exited
}
I have a List (listOfQuestionIDs) stored in ViewState of 10 different numbers and an int counter (questionCounter) stored in ViewState which I intend to use to access the different numbers in the first list.
However, as I increment the value of ViewState["questionCounter"] by 1 the contents of listOfAnswerIDs and listOfAnswers remain exactly the same in the code below. Why is this?
protected void getAnswers()
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
MySqlDataReader reader;
List<int> listOfQuestionIDs = (List<int>)(ViewState["listOfQuestionIDs"]);
int questionCounter = Convert.ToInt32(ViewState["questionCounter"]);
List<string> listOfAnswerIDs = new List<string>();
List<string> listOfAnswers = new List<string>();
List<string> listOfCorrectAnswerIDs = new List<string>();
try
{
conn.Open();
string cmdText = "SELECT * FROM answers WHERE question_id=#QuestionID";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#QuestionID", MySqlDbType.Int32);
cmd.Parameters["#QuestionID"].Value = Convert.ToInt32(listOfQuestionIDs[questionCounter]);
reader = cmd.ExecuteReader();
while (reader.Read())
{
listOfAnswerIDs.Add(reader["answer_id"].ToString());
listOfAnswers.Add(reader["answer"].ToString());
if (reader["correct"].ToString().Equals("Y"))
{
listOfCorrectAnswerIDs.Add(reader["answer_id"].ToString());
}
}
for (int i = 0; i < listOfAnswerIDs.Count; i++)
{
lblTitle.Text += listOfAnswerIDs[i].ToString();
}
reader.Close();
populateAnswers(listOfAnswerIDs.Count, listOfAnswers, listOfAnswerIDs);
}
catch
{
lblError.Text = "Database connection error - failed to read records.";
}
finally
{
conn.Close();
}
ViewState["listOfQuestionIDs"] = listOfQuestionIDs;
ViewState["listOfCorrectAnswerIDs"] = listOfCorrectAnswerIDs;
}
Here's where I increment the questionCounter:
protected void btnNext_Click(object sender, EventArgs e)
{
.........
getNextQuestion();
}
protected void getNextQuestion()
{
int questionCounter = Convert.ToInt32(ViewState["QuestionCounter"]);
..........
getAnswers();
................
questionCounter += 1;
ViewState["QuestionCounter"] = questionCounter;
}
ViewState keys are case sensitive. In getAnswers() you use "questionCounter" and in getNextQuestion() you use "QuestionCounter". Pick one and keep it consistent.
Hi im new to programming and currently working on a project that lets a user enter its
registration data into a local database using textBoxes. The code works that its adding the items into the database
and after i press a "Show_users" button it displays them in the listBox_users listbox.
My problem is that when i choose a name from the listBox_users it should dislay the data about the selected user in the upper textBox'es i used to enter
the data in the first place using the event i created for the listBox_users,
but im getting an error that "can't read data from database that is already closed".
namespace Userform
{
public partial class Form1: Form
{
SqlCeDataReader rdr;
public Form1()
{
InitializeComponent();
}
// Some code between...
private void button_ShowUsers_Click(object sender, EventArgs e) //code that shows users in listBox
{
var dt = new DataTable();
string connectionString2 = #"Data Source=MyDatabase;Password=xxxxxx;";
using (var cn = new SqlCeConnection(connectionString2))
using (var cmd = new SqlCeCommand("Select * From Users", cn))
{
cn.Open();
using (var reader = cmd.ExecuteReader())
{
dt.Load(reader);
var results = (from row in dt.AsEnumerable()
select new
{
//UserID = row.Field<int>("ID"),
FirstName = row.Field<string>("Firsname"),
LastName = row.Field<string>("Lastname"),
FullName = row.Field<string>("Firstname") + " " + row.Field<string>("Lastname")
}).ToList();
listBox_users.DataSource = results;
listBox_users.DisplayMember = "FullName";
rdr = cmd.ExecuteReader();
}
}
}
//I made an event for the listBox_users:
private void listBox_users_SelectedIndexChanged(object sender, EventArgs e)
//event code that should show listbox selected data in the textBoxes
{
if (listBox_inimesed.SelectedItem != null && rdr != null)
{
try
{
if (rdr.Read())
{
textBox1_firstname.Text = rdr.GetString(1);
textBox2_lastname.Text = rdr.GetString(2);
textBox3_email.Text = rdr.GetString(3);
textBox4_address.Text = rdr.GetString(4);
dateTimePicker1.Value = rdr.GetDateTime(5);
richTextBox_info.Text = rdr.GetString(6);
}
else MessageBox.Show("Object not found");
}
finally
{
rdr.Close();
}
}
}
}
The connection that the reader you are using is dependent on has been closed in the button_ShowUsers_Click event.
It is not a good practice to try to share connections and DataReaders across events. That will result in open connections that are not disposed of correctly. A better practice would be to have the creation of the Connection, Command, and DataReader take place in each event method. By using the "using" statement they will be closed and disposed of correctly in each method. You can also remove the class level variable "rdr".
namespace Userform
{
public partial class Form1 : Form
{
const string connectionString2 = #"Data Source=MyDatabase;Password=xxxxxx;";
public Form1()
{
InitializeComponent();
}
// Some code between...
private void button_ShowUsers_Click(object sender, EventArgs e) //code that shows users in listBox
{
var dt = new DataTable();
using (var cn = new SqlCeConnection(connectionString2))
using (var cmd = new SqlCeCommand("Select * From Users", cn))
{
cn.Open();
using (var reader = cmd.ExecuteReader())
{
dt.Load(reader);
var results = (from row in dt.AsEnumerable()
select new
{
//UserID = row.Field<int>("ID"),
FirstName = row.Field<string>("Firsname"),
LastName = row.Field<string>("Lastname"),
FullName = row.Field<string>("Firstname") + " " + row.Field<string>("Lastname")
}).ToList();
listBox_users.DataSource = results;
listBox_users.DisplayMember = "FullName";
}
}
}
//I made an event for the listBox_users:
private void listBox_users_SelectedIndexChanged(object sender, EventArgs e)
//event code that should show listbox selected data in the textBoxes
{
if (listBox_inimesed.SelectedItem != null)
{
using (var cn = new SqlCeConnection(connectionString2))
using (var cmd = new SqlCeCommand("Select * From Users", cn))
{
cn.Open();
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
textBox1_firstname.Text = reader.GetString(1);
textBox2_lastname.Text = reader.GetString(2);
textBox3_email.Text = reader.GetString(3);
textBox4_address.Text = reader.GetString(4);
dateTimePicker1.Value = reader.GetDateTime(5);
richTextBox_info.Text = reader.GetString(6);
}
else MessageBox.Show("Object not found");
}
}
}
}
}
}