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();
}
}
}
Related
I want to delete row from my database and also datagridview but it is only delete it in DataGridView,the row still in my database. How can I update my database?
I have found solutions in Internet but they didn't work.
Note: My database is opening in constructor.
My Code:
private void button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
for (int i = 0; i < UserListDataGridView.Rows.Count; i++)
{
DataGridViewRow row = UserListDataGridView.Rows[i];
if (row.Selected == true)
{
UserListDataGridView.Rows.RemoveAt(i);
cmd.CommandText = "DELETE FROM UserList WHERE user_id=" + i + "";
cmd.Connection = DBHelper.DBConnection.ConnectionString;
cmd.ExecuteNonQuery();
}
}
}
I found a solution. This code is working :
private void DeleteButton_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in this.UserListDataGridView.SelectedRows)
{
SqlCommand cmd = DBHelper.DBConnection.ConnectionString.CreateCommand();
int id = Convert.ToInt32(UserListDataGridView.SelectedRows[0].Cells[0].Value);
cmd.CommandText = "Delete from UserList where user_id='" + id + "'";
UserListDataGridView.Rows.RemoveAt(this.UserListDataGridView.SelectedRows[0].Index);
cmd.ExecuteNonQuery();
}
}
I want to create the attached task scheduler using asp.net and C#.
In SQL Server I have a table with these columns:
InstituteId, InstituteName, Address,
CareerDay2017 (date), CareerDay2018 (date), CareerDay2019 (date)
Dropdown list has values 2017, 2018, 2019. A button should be next to the dropdownlist.
When we select the year from dropdown list and click the button particular data should be retrieved and displayed as the image.
The career day details should be retrieved and colored the particular cell.
This is what I have tried, but it is incorrect. Hope you have taken my idea and help me.
SqlConnection con = new SqlConnection(#"Data Source=NAWODA;Initial Catalog=InternsDB;Integrated Security=True");
SqlCommand cmd;
SqlDataReader sdr,sdr1, sdr2;
String query;
DateTime current = DateTime.Now;
String dateColumn;
StringBuilder table = new StringBuilder();
protected void Page_Load(object sender, EventArgs e)
{
searchDetailPanel.Visible = false;
searchTaskPanel.Visible = false;
if (!Page.IsPostBack)
{
con.Open();
{
query = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CareerDay2018) = '2018'
ORDER BY InstituteId";
cmd = new SqlCommand(query, con);
sdr1 = cmd.ExecuteReader();
}
setData(sdr1, currentDetailPanel);
{
query = #"SELECT CareerDay2017, CareerDay2018, CareerDay2019
FROM Institution
ORDER BY InstituteId";
cmd = new SqlCommand(query, con);
sdr2 = cmd.ExecuteReader();
}
createYearTable(sdr1, sdr2, currentTaskPanel);
}
}
private void setData(SqlDataReader sdr, Panel DetailPanel1)
{
table.Append("<table>");
table.Append("<tr><th>Institute ID</th> <th>Institute Name</th>");
table.Append("</tr>");
if (sdr.HasRows)
{
while (sdr.Read())
{
table.Append("<tr>");
table.Append("<td>" + sdr[0] + "</td>");
table.Append("<td>" + sdr[1] + "</td>");
table.Append("</tr>");
}
}
table.Append("</table>");
DetailPanel1.Controls.Add(new Literal { Text = table.ToString() });
sdr.Close();
sdr.Dispose();
}
private void createYearTable(SqlDataReader sdr1,SqlDataReader sdr2, Panel DetailPanel2)
{
int currentYear = Int32.Parse(current.ToString("yyyy"));
table.Append("<table>");
//****filling the year
table.Append("<tr>");
for (int i = 1; i <= 12; i++)
{
table.Append("<td>" + Convert.ToString(currentYear) + "</td>");
}
table.Append("</tr>");
//****filling the month
table.Append("<tr>");
for (int j = 1; j <= 12; j++)
{
int monthString = j;
table.Append("<td>" +getMonthName(monthString) + "</td>");
}
table.Append("</tr>");
//****data cell filling
if (sdr2.HasRows)
{
while (sdr2.Read())
{
table.Append("<tr>");
if (yearDropDownList.SelectedValue == "2017")
{
dateColumn = sdr2[5].ToString();
DateTime careerFairDate = Convert.ToDateTime(dateColumn);
int monthNo = Int32.Parse(careerFairDate.ToString("MM"));
int dateNo = Int32.Parse(careerFairDate.ToString("dd"));
for (int j = 1; j <= 12; j++)
{
if (monthNo == j)
{
table.Append("<td>");
Label lbl1 = new Label();
lbl1.Text = "On" + dateNo;
table.Append("</td>");
}
else
{
table.Append("<td>");
Label lbl2 = new Label();
table.Append("</td>");
}
}
}
table.Append("</tr>");
}
table.Append("</table>");
DetailPanel2.Controls.Add(new Literal { Text = table.ToString() });
sdr2.Close();
sdr2.Dispose();
}
}
protected String getMonthName(int i)
{
String[] monthName = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
return monthName[i - 1];
}
protected void searchBtn_Click(object sender, EventArgs e)
{
currentDetailPanel.Visible = false;
currentTaskPanel.Visible = false;
searchDetailPanel.Visible = true;
searchTaskPanel.Visible = true;
con.Open();
if (yearDropDownList.SelectedValue == "2018")
{
query = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CareerDay2018) = '2018'
ORDER BY InstituteId";
}
else if (yearDropDownList.SelectedValue == "2017")
{
query = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CareerDay2017) = '2017'
ORDER BY InstituteId";
}
else if (yearDropDownList.SelectedValue == "2019")
{
query = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CareerDay2019) = '2019'
ORDER BY InstituteId";
}
cmd = new SqlCommand(query, con);
sdr = cmd.ExecuteReader();
setData(sdr, searchDetailPanel);
DateTime current = DateTime.Now;
createYearTable(sdr,sdr2,searchTaskPanel);
}
As for the UI part, you need to place a breakpoint in the method that draws your UI and step through it while it is reading your data. You need to learn how to debug you code.
Just based off what you have posted, I think you have a bigger issue, you should not be declaring a SqlConnection at the class level, it should be in a method somewhere. For example:
public void GetCalendarData(int year)
{
// You need to use a parameter for the year instead of hard-coding it (note the #year)
string strCmd = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CarrerDay2018) = #year
ORDER BY InstituteId";
using(var conn = new SqlConnection(connString))
using(var cmd = new SqlCommand(strCmd))
{
// add the #year parameter to the command
cmd.Parameters.AddWithValue("#year", year);
conn.Open();
var reader = cmd.ExecuteReader();
// setdata, createYearTable, etc.
conn.Close();
}
}
This way you are not holding a connection to the database for any longer than you need to. Also, I have put the connection and the command inside using statements, meaning that they will be disposed of properly by the garbage collector.
I have a dropdown list and an add button. When the add button is clicked, the selected item from the dropdown is supposed to be added to a database. However the selectedIndex value used in the function called by the add button is wrong. It doesn't match the actual index of the currently selected item (most of the time.)
Here is the dropdown and the button:
<asp:DropDownList runat="server" id="ddlNewCreature" AutoPostBack = "false" DataMember="0"></asp:DropDownList>
<asp:Button ID="btnAddCreature" runat="server" Text="Add" onClick="AddCreature"/>
Here is the code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (ddParent1.Items.Count == 0)
{
if (ddBaby.Items.Count == 0)
{
loadCreatureLists(true, true);
}
else
{
loadCreatureLists(true, false);
}
}
else
{
if (ddBaby.Items.Count == 0)
{
loadCreatureLists(false, true);
}
}
}
}
protected void loadCreatureLists(Boolean loadParents, Boolean loadOffspring )
{
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["Drin"].ConnectionString);
string sSql = "select creature, element1, element2 from dbo.tinycastlecreatures order by creature";
SqlCommand cmd = new SqlCommand(sSql, conn);
SqlDataReader reader;
try
{
conn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem = new ListItem();
newItem.Text = reader["creature"].ToString();
newItem.Value = normalizeElementOrder(reader["element1"].ToString(),reader["element2"].ToString());
if (loadParents && !chkMine.Checked)
{
ddParent1.Items.Add(newItem);
ddParent2.Items.Add(newItem);
}
if (loadOffspring)
{
ddBaby.Items.Add(newItem);
ddlNewCreature.Items.Add(newItem);
}
}
reader.Close();
}
catch (Exception err) { }
finally { if (!loadParents || !chkMine.Checked) { conn.Close(); } }
}
protected void AddCreature(object sender, EventArgs e)
{
int indx = ddlNewCreature.SelectedIndex;
string sCreature = ddlNewCreature.Items[indx].Text.ToString();
for (int i = 0; i < ddlNewCreature.Items.Count; i++ )
{
sCreature = ddlNewCreature.Items[i].Text.ToString();
}
ddlNewCreature.SelectedIndex = 0;
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["Drin"].ConnectionString);
conn.Open();
string sSql = "[dbo].[tinycastle_add_user_creature] '";
sSql += sCreature;
sSql += "','deb'";
SqlCommand cmd = new SqlCommand(sSql, conn);
cmd.ExecuteNonQuery();
sCreature = ddlNewCreature.Items[indx].Text.ToString();
sqlMineSource.DataBind();
gridMine.DataBind();
}
B.Yaylaci's suggestion on checking the SelectedIndex in the dropdown's changed event is on the right track to find out why (when? :)) the index isn't matching up with what you expect, I think.
Also, it'd be much easier (and more-accurate) to use the SelectedValue property if all you need is the text in the dropdown.
https://stackoverflow.com/a/4399747
I circumvented the problem by ripping out the way the various drop down lists were populated, and binding them to a SQLDataStore instead. I don't know why that helped, but it did.
Use ddlNewCreature.SelectedValue this will fix your problem." SelectedValue " give you the correct index value for the selected DropDownList. This worked for me.
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);
}
}
I had this message
Input string was not in a correct format
when inserting values into the database. When I checked I have DDL but I did not select value from it so this message appeared, although I make this column in the database to allow NULL value.
protected void BT_submit_Click(object sender, ImageClickEventArgs e)
{
string File = "~/CvFiles/" + FU_CV.FileName;
if (FU_CV.FileBytes.Length > 4194304)
{
modalpopup.Show();
}
else
{
app.AddApplicant(txt_Mname.Text, Convert.ToInt32(DDL_Dept.SelectedValue));
}
}
private void loadDepts()
{
DDL_Dept.DataSource = d.GetAll();
DDL_Dept.Items.Clear();
DDL_Dept.AppendDataBoundItems = true;
DDL_Dept.Items.Insert(0, new ListItem("-All-", "NULL"));
DDL_Dept.DataValueField = "id";
DDL_Dept.DataTextField = "name";
DDL_Dept.DataBind();
}
public bool AddApplicant(string MiddleName, int Dept_ID)
{
SqlCommand cmd = new SqlCommand("SP_Insert_IntoApplicantforuser");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#MiddleName", MiddleName);
cmd.Parameters.AddWithValue("#Dept_ID", Dept_ID);
System.Data.SqlClient.SqlParameter paramter1 = cmd.Parameters.Add("#AppID", SqlDbType.Int);
paramter1.Direction = ParameterDirection.Output;
bool rowaffected;
rowaffected = DBHelper.Instance().Insert(cmd);
if (rowaffected == false)
{
AppID = (int)paramter1.Value;
}
return rowaffected;
}
You should check, if DDL_Dept.SelectedValue is a string representation of int. Use int.TryParse method:
if (FU_CV.FileBytes.Length > 4194304)
{
modalpopup.Show();
}
else
{
int dept;
if (int.TryParse(DDL_Dept.SelectedValue, out dept))
app.AddApplicant(txt_Mname.Text, dept);
else
app.AddApplicant(txt_Mname.Text, -1); //or whatever there should be for you
}