I have problem with button click event and post back. I have a page with some textboxes and some drop-down lists. I fill those textboxes and ddls from database. I also have 2 buttons. One of them is updating database with changed data from textboxes and drop-down lists. Second button is displaying additional data depending on value from one of the drop-down list. My problem is that when I click update button the database is updated and data in textboxes and ddls are changed but when I enter into address tab and push Enter I got old data (In database everything is changed into new values). I could add method to
if (IsPostBack)
and data will be always fresh but in that case I will not be able to change value in one of the drop down list which displays additional data (Auto post back will load data into this ddl). Is there any workaround to this? If my description is not clear, please let me know.
EDIT1 Adding C# code
public partial class EditStaff : System.Web.UI.Page
{
Methods methods = new Methods();
IPrincipal p = HttpContext.Current.User;
protected void Page_Load(object sender, EventArgs e)
{
string soeid = Convert.ToString(Request["soeid"]);
DataSet dsUserDetails = new DataSet();
DataTable dtUserDetails = new DataTable();
DataSet dsDDLs = new DataSet();
if (!IsPostBack)
{
GetDDLsItems();
FillFields();
}
else
{
//FillFields();
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
string update_error = "";
string SOEID = txtSOEID.Text;
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
string email = txtEmail.Text.Trim();
int remsCode = Convert.ToInt32(ddlREMS.SelectedItem.ToString());
int active = Convert.ToInt32(ddlActive.SelectedValue);
int isGVO = Convert.ToInt32(ddlIsGVO.SelectedValue);
int gvoTeamID = Convert.ToInt32(ddlGVOTeams.SelectedValue);
int profileID = Convert.ToInt32(ddlProfiles.SelectedValue);
int isSOW = Convert.ToInt16(ddlIsSOW.SelectedValue);
int headcount = Convert.ToInt32(ddlHeadcount.SelectedValue);
string updater_domain = p.Identity.Name.ToString();
string updater = "";
int index = updater_domain.IndexOf("\\");
int email_at_index = email.IndexOf("#");
if (index != -1)
{
updater = updater_domain.Substring(index + 1, 7);
}
else
{
updater = updater_domain;
}
if (firstName.Length < 2)
{
update_error = "First Name should have at least 2 characters. ";
lblStatus.Text = update_error;
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Visible = true;
}
else if (lastName.Length < 2)
{
update_error = update_error + "Last Name should have at least 2 characters. ";
lblStatus.Text = update_error;
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Visible = true;
}
else if (email_at_index == -1 && email.Length < 5)
{
update_error = update_error + "Invalid email address.";
lblStatus.Text = update_error;
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Visible = true;
}
else
{
// create ConnectDatabase object to get acces to its methods
ConnectDatabase connectDB = new ConnectDatabase();
IDBManager dbManager = connectDB.ConnectDB();
DataSet ds = new DataSet();
try
{
dbManager.Open();
dbManager.CreateParameters(13);
dbManager.AddParameters(0, "#SOEID", SOEID);
dbManager.AddParameters(1, "#firstName", firstName);
dbManager.AddParameters(2, "#LastName", lastName);
dbManager.AddParameters(3, "#Email", email);
dbManager.AddParameters(4, "#REMSCode", remsCode);
dbManager.AddParameters(5, "#Active", active);
dbManager.AddParameters(6, "#IsGVO", isGVO);
dbManager.AddParameters(7, "#gvoTeamID", gvoTeamID);
dbManager.AddParameters(8, "#profileID", profileID);
dbManager.AddParameters(9, "#isSOW", isSOW);
dbManager.AddParameters(10, "#headcount", headcount);
dbManager.AddParameters(11, "#lastUpdatedBy", updater);
dbManager.AddParameters(12, "#status", active);
dbManager.ExecuteNonQuery(CommandType.StoredProcedure, "sp_update_user");
}
catch (Exception error)
{
HttpContext.Current.Response.Write(error.ToString());
}
finally
{
dbManager.Close();
dbManager.Dispose();
lblStatus.Visible = true;
lblStatus.Text = "User data updated successfully.";
lblStatus.ForeColor = System.Drawing.Color.Green;
FillFields();
}
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
FillFields();
gvREMSDetails.Visible = false;
}
private void FillFields()
{
string soeid = Convert.ToString(Request["soeid"]);
DataSet dsUserDetails = new DataSet();
DataTable dtUserDetails = new DataTable();
DataSet dsDDLs = new DataSet();
dsUserDetails = GetUserDetails(soeid);
dtUserDetails = dsUserDetails.Tables[0];
string gvoTeam = dtUserDetails.Rows[0].ItemArray[8].ToString();
string profile = dtUserDetails.Rows[0].ItemArray[10].ToString();
string remsCode = dtUserDetails.Rows[0].ItemArray[4].ToString();
txtSOEID.Text = dtUserDetails.Rows[0].ItemArray[0].ToString();
txtFirstName.Text = dtUserDetails.Rows[0].ItemArray[1].ToString();
txtLastName.Text = dtUserDetails.Rows[0].ItemArray[2].ToString();
txtEmail.Text = dtUserDetails.Rows[0].ItemArray[3].ToString();
ddlREMS.SelectedValue = remsCode.ToString();
txtAddress.Text = dtUserDetails.Rows[0].ItemArray[5].ToString();
//Response.Write((Convert.ToInt16(dtUserDetails.Rows[0].ItemArray[6])).ToString());
ddlActive.SelectedValue = (Convert.ToInt16(dtUserDetails.Rows[0].ItemArray[6])).ToString();
ddlIsGVO.SelectedValue = (Convert.ToInt16(dtUserDetails.Rows[0].ItemArray[7])).ToString();
ddlGVOTeams.SelectedValue = gvoTeam;
ddlProfiles.SelectedValue = profile;
ddlIsSOW.SelectedValue = (Convert.ToInt16(dtUserDetails.Rows[0].ItemArray[12])).ToString();
lblLastUpdatedBy_value.Text = dtUserDetails.Rows[0].ItemArray[14].ToString();
lblLastUpdatedDate_value.Text = dtUserDetails.Rows[0].ItemArray[15].ToString();
}
protected void btnGetREMSdetails_Click(object sender, EventArgs e)
{
//int remsCode = Convert.ToInt32(ddlREMS.SelectedValue);
// create ConnectDatabase object to get acces to its methods
ConnectDatabase connectDB = new ConnectDatabase();
IDBManager dbManager = connectDB.ConnectDB();
DataSet ds = new DataSet();
try
{
dbManager.Open();
dbManager.CreateParameters(1);
dbManager.AddParameters(0, "#remscode", Convert.ToInt32(ddlREMS.SelectedValue));
ds = dbManager.ExecuteDataSet(CommandType.Text, "select * from vwREMSDetails where [rems code] = #remscode");
gvREMSDetails.DataSource = ds;
gvREMSDetails.DataBind();
gvREMSDetails.Visible = true;
}
catch (Exception error)
{
HttpContext.Current.Response.Write(error.ToString());
}
finally
{
dbManager.Close();
dbManager.Dispose();
}
}
private static DataSet GetUserDetails(string soeid)
{
// create ConnectDatabase object to get acces to its methods
ConnectDatabase connectDB = new ConnectDatabase();
IDBManager dbManager = connectDB.ConnectDB();
DataSet ds = new DataSet();
try
{
dbManager.Open();
dbManager.CreateParameters(1);
dbManager.AddParameters(0, "#soeid", soeid);
ds = dbManager.ExecuteDataSet(CommandType.Text, "select * from vwUsersDetails where soeid = #soeid");
}
catch (Exception error)
{
HttpContext.Current.Response.Write(error.ToString());
}
finally
{
dbManager.Close();
dbManager.Dispose();
}
return ds;
}
private void GetDDLsItems()
{
// create ConnectDatabase object to get acces to its methods
ConnectDatabase connectDB = new ConnectDatabase();
IDBManager dbManager = connectDB.ConnectDB();
DataSet ds = new DataSet();
try
{
dbManager.Open();
ds = dbManager.ExecuteDataSet(CommandType.StoredProcedure, "sp_select_edit_user_ddls");
ddlREMS.DataSource = ds.Tables[0];
ddlREMS.DataTextField = "remsCode";
ddlREMS.DataValueField = "remsCode";
ddlREMS.DataBind();
ddlActive.DataSource = ds.Tables[1];
ddlActive.DataTextField = "Active";
ddlActive.DataValueField = "ActiveID";
ddlActive.DataBind();
ddlIsGVO.DataSource = ds.Tables[2];
ddlIsGVO.DataTextField = "IsGVO";
ddlIsGVO.DataValueField = "IsGVOID";
ddlIsGVO.DataBind();
//methods.GetGVOFunctions(ddlGVOFunctions);
//int? gvoFunctionID = string.IsNullOrEmpty(ddlGVOFunctions.SelectedValue) ? (int?)null : (int?)Convert.ToInt32(ddlGVOFunctions.SelectedValue);
methods.GetGVOTeams(null, ddlGVOTeams);
ddlProfiles.DataSource = ds.Tables[3];
ddlProfiles.DataTextField = "profilename";
ddlProfiles.DataValueField = "profileID";
ddlProfiles.DataBind();
ddlIsSOW.DataSource = ds.Tables[4];
ddlIsSOW.DataTextField = "IsSOW";
ddlIsSOW.DataValueField = "IsSOWID";
ddlIsSOW.DataBind();
ddlHeadcount.DataSource = ds.Tables[5];
ddlHeadcount.DataTextField = "Headcount";
ddlHeadcount.DataValueField = "HeadcountID";
ddlHeadcount.DataBind();
}
catch (Exception error)
{
HttpContext.Current.Response.Write(error.ToString());
}
finally
{
dbManager.Close();
dbManager.Dispose();
}
}
}
I'm not 100% I completly understand the issue, but it sounds to me that you need to have
if(!IsPostBack)
{
// load dropdown data here
}
where you load all your data into the dropdowns, and then on the dropdown have
<asp:DropDownList SelectedIndexChanged="ddlDropdown_SelectedIndexChanged" id="ddlDropdown" AutoPostBack="true"></asp:DropDownList>
Then in your code behind have
protected void ddlDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
}
Related
I want to put this into a loop, the code is working fine
but I can't make a loop for it.
When it detects a new data on a table it will automatically add
another item, on my code below it only shows two user controls but I need to generate all of the value in the table.
Here is the code
public partial class Form1 : Form
{
MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;database=rmsdb;username=root;password=");
MySqlCommand command;
MySqlDataAdapter da;
public Form1()
{
InitializeComponent();
LRNincrement();
}
int poss = 10;
public void AddItems(string Text, bool Checked)
{
DynaItems item = new DynamicUserControl.DynaItems(Text, Checked);
PanelContainer.Controls.Add(item);
item.Top = poss;
poss = (item.Top + item.Height + 10);
}
private void additembtn_Click(object sender, EventArgs e)
{
LRNincrement();
txt.Text = "";
}
private void LRNincrement()
{
String selectQuery = "SELECT lrnnumber from rmsdb.studentstable";
command = new MySqlCommand(selectQuery, connection);
da = new MySqlDataAdapter(command);
DataTable table = new DataTable();
da.Fill(table);
if (table.Rows.Count > 0)
{
string trylol = table.Rows[0][0].ToString();
AddItems(trylol, true);
}
if (table.Rows.Count > 1)
{
string trylol1 = table.Rows[1][0].ToString();
AddItems(trylol1, true);
}
}
}
Replace the below the code
{
string trylol = table.Rows[0][0].ToString();
AddItems(trylol, true);
}
if (table.Rows.Count > 1)
{
string trylol1 = table.Rows[1][0].ToString();
AddItems(trylol1, true);
}
with
string itemName = string.Empty;
for(int i = 0; i< table.Rows.Count; i++)
{
itemName = table.Rows[i][0].ToString();
AddItems(itemName, true);
}
I am not able to test this code. But hope this help you to find the solution.
I have requirement to create a survey web form which should be loaded from database.
Each questions will have 10 rating items from 1-10 and the result should be saved to the database with question number.
I tried to achieve it with a web form with label control at the top and RadioButtonList for options, but only one question and answer is possible to load for display at a time. I'm new to web programming. If there is any working code sample or any idea how to achieve this, it would be helpful.
I've done the coding to put each question on page and on button click I am loading the next question, but I need all the questions on a single page.
public partial class _Default : System.Web.UI.Page
{
public static SqlConnection sqlconn;
protected string PostBackStr;
protected void Page_Load(object sender, EventArgs e)
{
sqlconn = new SqlConnection(ConfigurationManager.AppSettings["sqlconnstr"].ToString());
PostBackStr = Page.ClientScript.GetPostBackEventReference(this, "time");
if (IsPostBack)
{
string eventArg = Request["__EVENTARGUMENT"];
if (eventArg == "time")
{
string str = "select * from tbl_Question";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "Question");
int count = ds2.Tables[0].Rows.Count;
getNextQuestion(count);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Visible = false;
txtName.Visible =false;
Button1.Visible = false;
Panel1.Visible = true;
lblName.Text = "Name : " + txtName.Text;
int score = Convert.ToInt32(txtScore.Text);
lblScore.Text = "Score : " + Convert.ToString(score);
Session["counter"]="1";
Random rnd = new Random();
int i = rnd.Next(1, 10);//Here specify your starting slno of question table and ending no.
//lblQuestion.Text = i.ToString();
getQuestion(i);
}
protected void Button2_Click(object sender, EventArgs e)
{
string str = "select * from tbl_Question ";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "Question");
int count = ds2.Tables[0].Rows.Count;
getNextQuestion(count);
}
public void getQuestion(int no)
{
string str = "select * from tbl_Question where slNo=" + no + "";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "Question");
// int count = ds2.Tables[0].Rows.Count;
if (ds2.Tables[0].Rows.Count > 0)
{
DataRow dtr;
int i = 0;
while (i < ds2.Tables[0].Rows.Count)
{
dtr = ds2.Tables[0].Rows[i];
Session["Answer"] = Convert.ToString(Convert.ToInt32 (dtr["Correct"].ToString())-1);
lblQuestion.Text = "Q." + Session["counter"].ToString() + " " + dtr["Question"].ToString();
lblQuestion2.Text = "Q." + Session["counter"].ToString() + " " + dtr["arQuestion"].ToString();
LblQNNo.Text = Session["counter"].ToString();
RblOption.ClearSelection();
RblOption.Items.Clear();
RblOption.Items.Add(dtr["Option1"].ToString());
RblOption.Items.Add(dtr["Option2"].ToString());
RblOption.Items.Add(dtr["Option3"].ToString());
RblOption.Items.Add(dtr["Option4"].ToString());
RblOption.Items.Add(dtr["Option5"].ToString());
RblOption.Items.Add(dtr["Option6"].ToString());
RblOption.Items.Add(dtr["Option7"].ToString());
RblOption.Items.Add(dtr["Option8"].ToString());
RblOption.Items.Add(dtr["Option9"].ToString());
RblOption.Items.Add(dtr["Option10"].ToString());
i++;
}
}
}
public void getNextQuestion(int cnt)
{
if (Convert.ToInt32(Session["counter"].ToString()) < cnt)
{
Random rnd = new Random();
int i = rnd.Next(1, 10);
lblQuestion.Text = i.ToString();
getQuestion(i);
//qst_no = i;
Session["counter"] = Convert.ToString(Convert.ToInt32(Session["counter"].ToString()) + 1);
}
else
{
Panel2.Visible = false;
//code for displaying after completting the exam, if you want to show the result then you can code here.
}
}
protected void Button3_Click(object sender, EventArgs e)
{
insertAns();
}
private void insertAns()
{
SqlCommand cmd;
sqlconn = new SqlConnection(ConfigurationManager.AppSettings["sqlconnstr"].ToString());
cmd = new SqlCommand("insert into Tbl_Ans(UserID, Question_ID, Answer) values(#ans, #ans1, #ans2)", sqlconn);
cmd.Parameters.AddWithValue("#ans", txtName.Text);
cmd.Parameters.AddWithValue("#ans1", Session["counter"].ToString());
cmd.Parameters.AddWithValue("#ans2", RblOption.SelectedItem.Text);
sqlconn.Open();
int i = cmd.ExecuteNonQuery();
sqlconn.Close();
if (i != 0)
{
lbmsg.Text = "Your Answer Submitted Succesfully";
lbmsg.ForeColor = System.Drawing.Color.ForestGreen;
}
else
{
lbmsg.Text = "Some Problem Occured";
lbmsg.ForeColor = System.Drawing.Color.Red;
}
}
#region Connection Open
public void ConnectionOpen()
{
try
{
if (sqlconn.State == ConnectionState.Closed) { sqlconn.Open(); }
}
catch (SqlException ex)
{
lbmsg.Text = ex.Message;
}
catch (SystemException sex)
{
lbmsg.Text = sex.Message;
}
}
#endregion
#region Connection Close
public void ConnectionClose()
{
try
{
if (sqlconn.State != ConnectionState.Closed) { sqlconn.Close(); }
}
catch (SqlException ex)
{
lbmsg.Text = ex.Message;
}
catch (SystemException exs)
{
lbmsg.Text = exs.Message;
}
}
#endregion
}
first i want to say that you should use question table id instead of question number to save with the answer for future use.
I dont know more about dotnet so i have not attached any code here. But i can suggest you that
First fetch all the questions with their respective id into an object or array or fetch from them adaptor etc.
Then you can use a form to show them using foreach loop. for eg.
suppose "questions" is an array containing your all fetched questions from database. then apply
<form action="abc" method="post">
foreach(questions as question){
<tr>
<td>(print your question here)</td>
<td><input type="anything you want" name="(print here question.id)" />
</tr>
}
<input type="submit" value="submit" />
</form>
Now where you will fetch data on the form submission then you can easily access the answers with their name that is already question id. So now both have associated with each other.
welcome for any query if not clear.
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'm trying to populate a generic collection but having problems. I'm trying to populate myBookings, which is supposed to store a List. The methods below should fill myBookings with the correct List but for some reason when I count the result (int c), I'm getting a return of 0. Can anyone see what I'm doing wrong?
// .cs
public partial class _Default : System.Web.UI.Page
{
iClean.Bookings myBookings = new iClean.Bookings();
iClean.Booking myBooking = new iClean.Booking();
iClean.Controller myController = new iClean.Controller();
ListItem li = new ListItem();
protected void Page_Load(object sender, EventArgs e)
{
CurrentFname.Text = Profile.FirstName;
CurrentUname.Text = Profile.UserName;
CurrentLname.Text = Profile.LastName;
myBookings.AllBookings = this.GetBookings();
int c = myBookings.AllBookings.Count();
Name.Text = c.ToString();
Address.Text = myBooking.Address;
Phone.Text = myBooking.Phone;
Date.Text = myBooking.DueDate.ToString();
Comments.Text = myBooking.Comments;
}
public List<iClean.Booking> GetBookings()
{
List<iClean.Booking> bookings = new List<iClean.Booking>();
ArrayList records = this.Select("Bookings", "");
for (int i = 0; i < records.Count; i++)
{
iClean.Booking tempBooking = new iClean.Booking();
Hashtable row = (Hashtable)records[i];
tempBooking.ID = Convert.ToInt32(row["ID"]);
tempBooking.Name = Convert.ToString(row["ClientName"]);
tempBooking.Address = Convert.ToString(row["ClientAddress"]);
tempBooking.Phone = Convert.ToString(row["ClientPhone"]);
tempBooking.DueDate = Convert.ToDateTime(row["Bookingdate"]);
tempBooking.Completed = Convert.ToBoolean(row["Completed"]);
tempBooking.Paid = Convert.ToBoolean(row["Paid"]);
tempBooking.Cancelled = Convert.ToBoolean(row["Cancelled"]);
tempBooking.ReasonCancelled = Convert.ToString(row["ReasonCancelled"]);
tempBooking.ContractorPaid = Convert.ToBoolean(row["ContractorPaid"]);
tempBooking.Comments = Convert.ToString(row["Comments"]);
tempBooking.Windows = Convert.ToBoolean(row["Windows"]);
tempBooking.Gardening = Convert.ToBoolean(row["Gardening"]);
tempBooking.IndoorCleaning = Convert.ToBoolean(row["IndoorCleaning"]);
bookings.Add(tempBooking);
}
return bookings;
}
public ArrayList Select(string table, string conditions)
{
// Create something to hosue the records.
ArrayList records = new ArrayList();
try
{
// Open a connection.
OleDbConnection myConnection = new OleDbConnection(this.getConnectionString());
myConnection.Open();
// Generate the SQL
string sql = "SELECT * FROM " + table;
if (conditions != "") { sql += " WHERE " + conditions; }
// Console.WriteLine("Select SQL: " + sql); // In case we need to debug
// Run the SQL
OleDbCommand myCommand = new OleDbCommand(sql, myConnection);
OleDbDataReader myReader = myCommand.ExecuteReader();
// Go through the rows that were returned ...
while (myReader.Read())
{
// ... create Hashtable to keep the columns in, ...
Hashtable row = new Hashtable();
// ... add the fields ...
for (int i = 0; i < myReader.FieldCount; i++)
{
row.Add(myReader.GetName(i), myReader[i]);
}
// ... and store the row.
records.Add(row);
}
// Make sure to close the connection
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return records;
}
public string getConnectionString()
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=IQQuotes.accdb;";
return connectionString;
}
}
Just a guess, but try this:
public List<iClean.Booking> GetBookings()
{
List<iClean.Booking> bookings = new List<iClean.Booking>();
ArrayList records = this.Select("Bookings", "");
iClean.Booking tempBooking = new iClean.Booking();
for (int i = 0; i < records.Count; i++)
{
tempBooking = new iClean.Booking();
Hashtable row = (Hashtable)records[i];
tempBooking.ID = Convert.ToInt32(row["ID"]);
tempBooking.Name = Convert.ToString(row["ClientName"]);
tempBooking.Address = Convert.ToString(row["ClientAddress"]);
tempBooking.Phone = Convert.ToString(row["ClientPhone"]);
tempBooking.DueDate = Convert.ToDateTime(row["Bookingdate"]);
tempBooking.Completed = Convert.ToBoolean(row["Completed"]);
tempBooking.Paid = Convert.ToBoolean(row["Paid"]);
tempBooking.Cancelled = Convert.ToBoolean(row["Cancelled"]);
tempBooking.ReasonCancelled = Convert.ToString(row["ReasonCancelled"]);
tempBooking.ContractorPaid = Convert.ToBoolean(row["ContractorPaid"]);
tempBooking.Comments = Convert.ToString(row["Comments"]);
tempBooking.Windows = Convert.ToBoolean(row["Windows"]);
tempBooking.Gardening = Convert.ToBoolean(row["Gardening"]);
tempBooking.IndoorCleaning = Convert.ToBoolean(row["IndoorCleaning"]);
bookings.Add(tempBooking);
}
return bookings;
}
Somebody please help me how to store the value dynamically using arraylist.Every time i want to add patient details. Here is my code layer wise:
PatientDataLayer:
public class PatientData
{
public string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
public int AddPatient(Patient obj)
{
using (var con = new SqlConnection(str))
{
using (var com = new SqlCommand("AddPatient", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", obj.Name);
com.Parameters.AddWithValue("#Address", obj.Address);
com.Parameters.AddWithValue("#DateOfBirth", obj.DateOfBirth);
com.Parameters.AddWithValue("#Phone", obj.Phone);
com.Parameters.AddWithValue("#EmergencyContact", obj.EmergencyContact);
com.Parameters.AddWithValue("#DateOfRegistration", obj.DateOfRegistration);
con.Open();
com.ExecuteNonQuery();
con.Close();
return 0;
}
}
}
PatientBusinessLayer:
public class PatientBusiness
{
public void Add(Patient obj)
{
PatientData pd = new PatientData();
pd.AddPatient(obj);
}
}
Patient.aspx.cs:
protected void BtnAdd_Click(object sender, EventArgs e)
{
if (!Page.IsValid) //validating the page
return;
string name = TxtName.Text;
string address = TxtAddress.Text;
DateTime dateofbirth =Convert.ToDateTime(TxtDateOfBirth.Text);
int phone = Convert.ToInt32(TxtPhone.Text);
int emergencyno=Convert.ToInt32(TxtContact.Text);
DateTime registrationdate =Convert.ToDateTime(TxtRegistrationDate.Text);
PatientBusiness PB = new PatientBusiness();
Patient obj = new Patient();
try
{
obj.Name = name;
obj.Address = address;
obj.DateOfBirth = dateofbirth;
obj.Phone = phone;
obj.EmergencyContact = emergencyno;
obj.DateOfRegistration = registrationdate;
PB.Add(obj);
LblMessage.Text = "Patient has been added successfully";
TxtName.Text = "";
TxtAddress.Text = "";
TxtDateOfBirth.Text = "";
TxtPhone.Text = "";
TxtContact.Text = "";
TxtRegistrationDate.Text = "";
}
catch (Exception ee)
{
LblMessage.Text = ee.Message.ToString();
}
finally
{
PB = null;
}
}
Thanks,
Masum
I don't understand your question but after reviewing your code, I can only recommand you to consider using an ObjectDataSource combined with a FormView and stop doing "business stuff" in code behind.