survey page in asp c# - c#

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.

Related

How to retrieve data from DataTable by iterating through the rows

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.

DataSet not updated with new row inserted in C#

i am trying to insert new row in Emp table in c# (disconnected mode), the new row successfully inserted but the dataset not updated, so when i search for the new row, i don't find it, but when i search for an old row, i find it.
the insertBTN button used to insert new row
the searchByID button used to search for row by its ID
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SqlConnection conn;
private SqlDataAdapter adapter;
private DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
conn = new SqlConnection(#"data source=(local);initial catalog =Test;integrated security = true");
conn.Open();
adapter = new SqlDataAdapter("select * from Emp",conn);
ds = new DataSet();
adapter.Fill(ds,"Emp");
}
private void insertBTN_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
string name = textBox2.Text;
string address = textBox3.Text;
int age = int.Parse(textBox4.Text);
int salary = int.Parse(textBox5.Text);
SqlCommand command = new SqlCommand("Insert into Emp values(" + id + ",'" + name + "','" + address + "'," + age + "," + salary + ")", conn);
command.ExecuteNonQuery();
adapter.Update(ds,"Emp");
MessageBox.Show("Employee added successfully");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
private void searchByID_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
foreach (DataRow row in ds.Tables["Emp"].Rows)
{
if (Convert.ToInt32(row["id"]) == id)
{
textBox2.Text = Convert.ToString(row["name"]);
textBox3.Text = Convert.ToString(row["address"]);
textBox4.Text = Convert.ToString(row["age"]);
textBox5.Text = Convert.ToString(row["salary"]);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The Update method of the DataAdapter doesn't read again but tries to execute the INSERT, DELETE and UPDATE commands derived from the original SELECT statement against the Rows in the DataTable that have their RowState changed
So, if you want to use the Update method of the adapter you could write
private void insertBTN_Click(object sender, EventArgs e)
{
try
{
DataRow row = ds.Tables["emp"].NewRow();
row.SetField<int>("id", int.Parse(textBox1.Text));
row.SetField<string>("name", textBox2.Text));
row.SetField<string>("address", textBox3.Text));
row.SetField<int>("age", int.Parse(textBox4.Text));
row.SetField<int>("salary", int.Parse(textBox5.Text));
ds.Tables["emp"].Rows.Add(row);
adapter.Update(ds,"Emp");
MessageBox.Show("Employee added successfully");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
At this point your DataSet contains the added row because you have added it manually and then passed everything to the Update method to write it to the database.
However, keep in mind that the Update method to work requires certain conditions to be present. You could read them in the DbDataAdapter.Update page on MSDN.
Mainly you need to have retrieved the primary key of the table, do not have more than one table joined together and you have used the DbCommandBuilder object to create the required commands (Again the example in the MSDN page explain it)
Not related to your question, but you could change your search method and avoid writing a loop to search for the ID
private void searchByID_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
DataRow[] foundList = ds.Tables["Emp"].Select("Id = " + id);
if(foundList.Length > 0)
{
textBox2.Text = foundList[0].Field<string>("name");
textBox3.Text = foundList[0].Field<string>("address");
textBox4.Text = foundList[0].Field<int>("age").ToString();
textBox5.Text = foundList[0].Field<int>("salary").ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool.

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
}

Postback vs Button_Click

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)
{
}

SqlDataAdapter.Update or SqlCommandBuilder not working

I have a form with a datagrid, which is populated wih data from a sqlserver database. The datagrid populates fine but I am having trouble posting back the changes made by the user, to the table in the sql database. My forms code is as follows:
public partial class frmTimesheet : Form
{
private DataTable tableTS = new DataTable();
private SqlDataAdapter adapter = new SqlDataAdapter();
private int currentTSID = 0;
public frmTimesheet()
{
InitializeComponent();
}
private void frmTimesheet_Load(object sender, EventArgs e)
{
string strUser = cUser.currentUser;
cMyDate cD = new cMyDate(DateTime.Now.ToString());
DateTime date = cD.GetDate();
txtDate.Text = date.ToString();
cboTSUser.DataSource = cUser.GetListOfUsers("active");
cboTSUser.DisplayMember = "UserID";
cboTSUser.Text = strUser;
CheckForTimeSheet();
PopulateTimeSheet();
}
private void CheckForTimeSheet()
{
string strUser = cboTSUser.Text;
cMyDate cD = new cMyDate(txtDate.Text);
DateTime date = cD.GetDate();
int newTSID = cTimesheet.TimeSheetExists(strUser, date);
if (newTSID != this.currentTSID)
{
tableTS.Clear();
if (newTSID == 0)
{
MessageBox.Show("Create TimeSheet");
}
else
{
this.currentTSID = newTSID;
}
}
}
private void PopulateTimeSheet()
{
try
{
string sqlText = "SELECT EntryID, CaseNo, ChargeCode, StartTime, FinishTime, Units " +
"FROM tblTimesheetEntries " +
"WHERE TSID = " + this.currentTSID + ";";
SqlConnection linkToDB = new SqlConnection(cConnectionString.BuildConnectionString());
SqlCommand sqlCom = new SqlCommand(sqlText, linkToDB);
SqlDataAdapter adapter = new SqlDataAdapter(sqlCom);
adapter.SelectCommand = sqlCom;
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Fill(tableTS);
dataTimesheet.DataSource = tableTS;
}
catch (Exception eX)
{
string eM = "Error Populating Timesheet";
cError err = new cError(eX, eM);
MessageBox.Show(eM + Environment.NewLine + eX.Message);
}
}
private void txtDate_Leave(object sender, EventArgs e)
{
CheckForTimeSheet();
PopulateTimeSheet();
}
private void cboTSUser_DropDownClosed(object sender, EventArgs e)
{
CheckForTimeSheet();
PopulateTimeSheet();
}
private void dataTimesheet_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
try
{
adapter.Update(tableTS);
}
catch (Exception eX)
{
string eM = "Error on frmTimesheet, dataTimesheet_CellValueChanged";
cError err = new cError(eX, eM);
MessageBox.Show(eM + Environment.NewLine + eX.Message);
}
}
}
No exception occurs, and when I step through the issue seems to be with the SqlCommandBuilder which does NOT build the INSERT / UPDATE / DELETE commands based on my gien SELECT command.
Can anyone see what I am doing wrong?
What am I missing?
You need to set the UpdateCommand instead of SelectCommand on update:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
The question is old, but the provided answer by#Anurag Ranjhan need to be corrected.
You need not to write the line:
adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
and enough to write:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
//remove the next line
//adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
The Sql update/insert/delete commands are auto generated based on this line
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
You can find the generated update sql by executing the line:
sqlBld.GetUpdateCommand().CommandText;
See the example How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visual C# .NET
The problem said by OP can be checked by reviewing the Sql Statement sent by the client in SQl Server Profiler.

Categories