Change calendar day back color - c#

I'm trying to save a day data from calendar and change it color to red after click on it . so the saved on in database will be in red color and unsaved will be in green color .
The problem is when i choose multiple days just the last one will change to red the previous one will stuck in green color .
The data is received from sql correctly i show it in text box and all saved days is appear
int[] arr;
dynamic ad;
protected void Page_Load(object sender, EventArgs e)
{
cn.Open();
SqlCommand c1 = new SqlCommand("select count(*) from app1", cn);
int count = int.Parse(c1.ExecuteScalar().ToString());
cn.Close();
arr = new int[count];
DataClassesDataContext db = new DataClassesDataContext();
ad =(from a in db.app1s select a.data).ToArray();
}
protected void Button1_Click(object sender, EventArgs e)
{
//id is int
SqlCommand cmd = new SqlCommand("insert into app1 values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + DropDownList1.SelectedValue + "')", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
foreach (var item in ad)
{
if (int.Parse(item) == int.Parse(Calendar1.SelectedDate.Day.ToString()))
{
Calendar1.SelectedDayStyle.BackColor = System.Drawing.Color.Red;
}
else
{
Calendar1.SelectedDayStyle.BackColor = System.Drawing.Color.Green;
TextBox5.Text = Calendar1.SelectedDate.Day.ToString();
}
}
}
I try to use array but same problem
int[] arr;
protected void Page_Load(object sender, EventArgs e)
{
cn.Open();
SqlCommand c1 = new SqlCommand("select count(*) from apoyt1", cn);
int count = int.Parse(c1.ExecuteScalar().ToString());
cn.Close();
arr = new int[count + 1];
for (int i = 1; i <= count; i++)
{
cn.Open();
SqlCommand cm = new SqlCommand("select data from apoyt1 where id='" + i + "'", cn);
arr[i] = int.Parse(cm.ExecuteScalar().ToString());
cn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//id is int
SqlCommand cmd = new SqlCommand("insert into apoyt1 values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + DropDownList1.SelectedValue + "')", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == int.Parse(Calendar1.SelectedDate.Day.ToString()))
{
Calendar1.SelectedDayStyle.BackColor = System.Drawing.Color.Red;
}
else {
Calendar1.SelectedDayStyle.BackColor = System.Drawing.Color.Green;
TextBox5.Text = Calendar1.SelectedDate.Day.ToString();
}
}
}

Your code is not doing the purpose that it should planed for, as well Calendar1.SelectedDayStyle.BackColor is always referring to same selected object. so try the following:
1) create a list for days, as number of days are unknown.
List<Int32> days;
protected void Page_Load(object sender, EventArgs e)
{
}
2) Because of each time the page is reloading you need to store these days in a session.
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
days = (List<int>)Session["var"];
if (days == null) days = new List<int>();
days.Add(Calendar1.SelectedDate.Day);
Session["var"] = days;
ListBox1.Items.Clear();
foreach (int d in days)
{
Calendar1.SelectedDates.Add(new DateTime(Calendar1.SelectedDate.Year, Calendar1.SelectedDate.Month, d));
Calendar1.SelectedDayStyle.BackColor = System.Drawing.Color.Red;
ListBox1.Items.Add(d.ToString());
}
}
3) i have uploaded a sample of code so you can check it Here

Related

Dropdown List Select index Default if no User Input

I have a dropdown list which works fine if the user selects one of the 6 options.
However if no action is taken because the first Option is the one required the selected value stays blank.
I have tried to set default selected value and search other solutions via Stack Overflow. Code Project, etc. but nothing works.
it may be something basic in my code!
static string prevPage = String.Empty;
protected void Page_Load(object sender, EventArgs e)
{
FileUpload1.Attributes["multiple"] = "multiple";
txtUN.Text = Request.QueryString["SVCCNo"];
lblid.Text = Session["username"].ToString();
txtCID.Text = Request.QueryString["CID"];
lblCID.Text = Request.QueryString["CID"];
lblSeparator.Text = " - ";
lblLocation.Text = Request.QueryString["LName"];
lblAssetName.Text = Request.QueryString["SVCCIDName"];
if (!IsPostBack)
{
prevPage = Request.UrlReferrer.ToString();
}
}
protected void Upload(object sender, EventArgs e)
{
string conn = ConfigurationManager.ConnectionStrings["SVCCAssetsDb"].ConnectionString;
SqlConnection sqlcon = new SqlConnection(conn);
sqlcon.Open();
//lblType.Text = "1";
for (int i = 0; i < Request.Files.Count; i++)
{
//move lbl inside loop
int uniquenuumber = Convert.ToInt32(txtUN.Text);
HttpPostedFile postedFile = Request.Files[i];
if (postedFile.ContentLength > 0)
{
//lblType.Text = txtType.Text;
int txttype = 1;
txttype = Convert.ToInt32(lblType.Text);
string userid = lblid.Text;
string fileName = Path.GetFileName(postedFile.FileName);
postedFile.SaveAs(Server.MapPath("~/Attachment/") + fileName);
lblMessage.Text += string.Format("<b>{0}</b> uploaded.<br />", fileName);
string sqlquery = "INSERT INTO Attachment (UserName, FilePath, UniqueNumber, TypeCode) VALUES ('" + userid + "', + '" + fileName + "', + '" + uniquenuumber + "', '" + txttype + "')";
SqlCommand sqlcmd = new SqlCommand(sqlquery, sqlcon);
sqlcmd.ExecuteNonQuery();
}
}
sqlcon.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var selectedValue = ((DropDownList)sender).SelectedValue;
if (!string.IsNullOrEmpty(txtType.Text))
txtType.Text = selectedValue;
lblType.Text = txtType.Text;
}
protected void btnReturn_Click(object sender, EventArgs e)
{
Response.Redirect(prevPage);
}
}
aspx code:
Multi-File Upload
Files Must be All of the Same Type e.g. Photographs
Select the File Type Before Selecting the Files to Upload
Otherwise Files Chosen will be Clear Cleared
From what I guess without having the front code :
You're having a problem with this line :
int txttype = 1;
txttype = Convert.ToInt32(lblType.Text);
Which is caused because if you don't select another item from your dropdown, your label isn't updated and so this create a problem ?
If that's the case (else just explain me where I'm wrong )
You could just do a first intialisation of your label Type at the page load (in the !Page.IsPostBack Condition !!)
lblType.Text = "Your Default value as string";
Indeed, the select index changed event will trigger only if you change the dropdown, which in the case, if you stay on the first item, will not be triggered.
But there's maybe something else, let's try that first ! :)
SOLVED! Just a matter of getting the Code Rejigged.
Code Now Reads:
string conn =
ConfigurationManager.ConnectionStrings["SVCCAssetsDb"].ConnectionString;
SqlConnection sqlcon = new SqlConnection(conn);
sqlcon.Open();
int txttype = Convert.ToInt32(lblType.Text);
for (int i = 0; i < Request.Files.Count; i++)
{
//move lbl inside loop
int uniquenuumber = Convert.ToInt32(txtUN.Text);
HttpPostedFile postedFile = Request.Files[i];
if (postedFile.ContentLength > 0)
{
//lblType.Text = txtType.Text;
//int txttype = 1;
txttype = Convert.ToInt32(lblType.Text);
string userid = lblid.Text;
string fileName = Path.GetFileName(postedFile.FileName);
postedFile.SaveAs(Server.MapPath("~/Attachment/") + fileName);
lblMessage.Text += string.Format("<b>{0}</b> uploaded.<br />",
fileName);
string sqlquery = "INSERT INTO Attachment (UserName, FilePath,
UniqueNumber, TypeCode) VALUES ('" + userid + "', + '" + fileName + "', + '" +
uniquenuumber + "', '" + txttype + "')";
SqlCommand sqlcmd = new SqlCommand(sqlquery, sqlcon);
sqlcmd.ExecuteNonQuery();
}
}
sqlcon.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var selectedValue = ((DropDownList)sender).SelectedValue;
if (!string.IsNullOrEmpty(txtType.Text))
txtType.Text = selectedValue;
lblType.Text = selectedValue;
}

Autocomplete comboBox that checks items in its list are entered

Is there a way to check when an item is entered in a comboBox, is only one in which is actually in the list? To explain further, if anything outside the list is selected it won't accept that input. I've looked within stackoverflow but the only solution am seeing is that of changing my comboBox style to a dropdown list style. The problem with this is that there are more than a hundred records to select from so the autocomplete on the comboBox is absolutely necessary to filter these out by the user input entered.
Updated(declared matched globally):
private void comboBox3_TextChanged(object sender, EventArgs e)
{
ComboBox c = ((ComboBox)sender);
string[] items = c.Items.OfType<string>().ToArray();
matched = items.Any(i => i == c.Text.Trim().ToLower());
}
and this is where it executes:
private void button5_Click(object sender, EventArgs e)
{
if (matched==false)
{
MessageBox.Show("Value in Carimed Items does not exist");
}else
{
if (string.IsNullOrEmpty(comboBox5.Text))
{
MessageBox.Show("Please select output file to be written to!");
}
else
{
// int current = 0;
if (comboBox1.Text.Trim() == string.Empty)
{
MessageBox.Show("All fields must be filled in before saving!");
}
else
{
// StringBuilder csvconten = new StringBuilder();
// csvconten.AppendFormat("{0},{1},{2},{3},{4},{5}\r\n", comboBox2.Text, textBox5.Text, textBox2.Text, comboBox3.Text, textBox3.Text, comboBox1.Text);
// string csvpath = "cross_check.csv";
// File.AppendAllText(csvpath, csvconten.ToString());
string connectionString3 = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacy_Output_File;Integrated Security=True";
string query3 = "INSERT INTO dbo.[" + comboBox5.Text + "] VALUES('" + comboBox2.Text + "','" + textBox5.Text.Replace("'", "''") + "','" + textBox7.Text.Replace("'", "''") + "','" + textBox2.Text.Replace("'", "''") + "','" + comboBox3.Text.Replace("'", "''") + "','" + textBox3.Text + "','" + comboBox1.Text + "');";
using (SqlConnection connection = new SqlConnection(connectionString3))
{
SqlCommand command = new SqlCommand(query3, connection);
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
}
// textBox1.Clear();
// textBox3.Clear();
// comboBox3.ResetText();
textBox2.Clear();
textBox3.Clear();
comboBox3.ResetText();
comboBox1.ResetText();
}
string connectionString2 = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
string query2 = "UPDATE Liguanea_Lane2 SET Progress= '1' where code = '" + comboBox2.Text + "'; ";
using (SqlConnection connection = new SqlConnection(connectionString2))
{
SqlCommand command = new SqlCommand(query2, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
//this.liguanea_ProgressTableAdapter1.Fill(this.pharmaciesDataSet7.Liguanea_Progress);
comboBox2.SelectedIndex = comboBox2.SelectedIndex + 1;
//current = liguaneaLane2BindingSource.Position;
//this.liguanea_Lane2TableAdapter.Fill(this.pharmaciesDataSet3.Liguanea_Lane2);
refreshDataGrid2();
if (dataGridView1.CurrentRow != null)
{
dataGridView1.CurrentCell =
dataGridView1
.Rows[Math.Min(dataGridView1.CurrentRow.Index + 1, dataGridView1.Rows.Count - 1)]
.Cells[dataGridView1.CurrentCell.ColumnIndex];
// liguaneaLane2BindingSource.Position = Math.Min(current + 1, liguaneaLane2BindingSource.Count - 1);
}
}
}
}
You can Use the TextChanged Event of the ComboBox to See if the enter text exsists in you list:
private void comboBox1_TextChanged(object sender, EventArgs e)
{
ComboBox c = ((ComboBox)sender);
string[] items = c.Items.OfType<string>().ToArray();
bool matched = items.Any(i => i == c.Text.Trim().ToLower());
}
You can declare the matched bool globally in the form that TextChanged event would assign its value then you can use it in other Methods like:
void Button_Click(object sender, e EventArgs){
if(matched)
{
//do something
} else{
// show an error message
}
}

Getting Index Value of Drop down list always stored as 0 in connected database.Also i have enabled the autopostback in html source [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Have include my C# code.Please help me to accomplish the task
namespace WebApplication1
{
public partial class Project1 : System.Web.UI.Page
{
OracleConnection con = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TEST"].ToString());
string str;
int compId;
protected void Page_Load(object sender, EventArgs e)
{
// calProjectDate.Visible = false;
if (!this.IsPostBack)
{
OracleConnection con = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TEST"].ToString());
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = " Select * FROM COMPANY";
cmd.Connection = con;
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
ddlCompanyName.DataSource = dt;
ddlCompanyName.DataTextField = "COMPANYNAME";
ddlCompanyName.DataValueField = "COMPANYID";
ddlCompanyName.DataBind();
ddlCompanyName.Items.Insert(0, new ListItem("--Select Name--"));
con.Close();
}
}
protected void btnShowCalendar_Click(object sender, ImageClickEventArgs e)
{
calProjectDate.Visible = true;
}
protected void calDateofBirth_SelectionChanged(object sender, EventArgs e)
{
txtProjectDate.Text = calProjectDate.SelectedDate.ToShortDateString();
calProjectDate.Visible = false;
}
protected void calProjectDate_SelectionChanged(object sender, EventArgs e)
{
txtProjectDate.Text = calProjectDate.SelectedDate.ToShortDateString();
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
con.Open();
OracleCommand cmd = con.CreateCommand();
str = ddlCompanyName.SelectedItem.Text;
//int value = ddlCompanyName.DataValueField.OfType.s;
// int selectedradioValue = this.RblGender.TabIndex;
// int selectedCompanyValue = this.ddlCompanyName.TabIndex;
cmd.CommandText = "INSERT INTO CMPPOJECT(PROJECTNAME,DESCRIPTION,COMPANY,WEBSITEURL,COMPLETEDIN,STARTEDIN)VALUES('" + txtProjectName.Text + "','" + txtDescription.Text + "','" + compId + "','" + txtWebsiteUrl.Text + "','" + cbProjectCompleted.Text + "','" + txtProjectDate.Text + "')";
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
Response.Write("<script>alert('Sorry,some error occured! Please try again!')</script>");
}
finally
{
con.Close();
Response.Write("is it coming");
}
}
protected void ddlCompanyName_SelectedIndexChanged(object sender, EventArgs e)
{
compId = ddlCompanyName.SelectedIndex;
}
}
}
the compId is always 0 because every time having new PostBack request, the compId is initialized and the default value is 0
You can directly use the value of dropdownlist (ddlCompanyName.SelectedValue):
cmd.CommandText = "INSERT INTO CMPPOJECT(PROJECTNAME,DESCRIPTION,COMPANY,WEBSITEURL,COMPLETEDIN,STARTEDIN)VALUES('" + txtProjectName.Text + "','" + txtDescription.Text + "','" + ddlCompanyName.SelectedValue + "','" + txtWebsiteUrl.Text + "','" + cbProjectCompleted.Text + "','" + txtProjectDate.Text + "')";

How to not catch the old data in page load

I trying to update my profile but it keep catching the old data when it update. What can be done to solve this problem. Please help me out on this problem thanks!
protected void Page_Load(object sender, EventArgs e)
{
String nric = (String)Session["nric"];
SqlConnection con = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI");
con.Open();
SqlCommand cm = new SqlCommand("Select * from MemberAccount where nric = '" + nric + "'", con);
SqlDataReader dr;
dr = cm.ExecuteReader();
if (dr.Read())
{
txtFullName.Text = dr["fullname"].ToString();
txtAddress.Text = dr["address"].ToString();
txtContact.Text = dr["contact"].ToString();
txtEmail.Text = dr["email"].ToString();
}
con.Close();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
String nric = (String)Session["nric"];
if (txtContact.Text.Equals("") || txtEmail.Text.Equals(""))
{
lblMessage.Text = "Do not leave blank fill to update your profile!";
}
else
{
string strQuery = "Update MemberAccount Set address = '" + txtAddress.Text + "', contact = '" + txtContact.Text + "', email = '" + txtEmail.Text + "' Where nric = '" + nric + "'";
SqlCommand cmd = new SqlCommand(strQuery);
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "Profile Updated.";
}
}
Sounds like you could just apply an IsPostBack check in your Page_Load method. http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
// Load data
}
}
Note: your code looks susceptible to SQL injection.

Cannot implicitly convert type 'WebApplication4.SqlConnection' to 'System.Data.SqlClient.SqlConnection' ~AddUser.aspx.cs

I have tried so many types I don't know how to insert.
Is there any problem with sql server?
PLEASE HELP ME FAST..
SqlConnection con = new SqlConnection( "Data Source=localhost/SQLEXPRESS.Polaris.dbo;Initial Catalog=Polaris;Integrated Security=True;Pooling=False");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void Button3_Click(object sender, EventArgs e)
{
con.Open();
SqlDataReader rdr = null;
//string s1 = "insert into Login values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Value + "'";
SqlCommand cmd1 = new SqlCommand("insert into Login values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Value + "'");
cmd1.Connection = con;
rdr = cmd1.ExecuteReader();
Label2.Visible = true;
//EndEventHandler.RemoveAll();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("WebForm1.aspx");
}
Cannot implicitly convert type 'WebApplication4.SqlConnection' to
'System.Data.SqlClient.SqlConnection'
According to error you have class called SqlConnection in WebApplication4 namespace. You may have mistakenly generate that class. you need to remove that class first and then add reference to System.Data.SqlClient
Here's what you can do:
SqlConnection con = new SqlConnection( "Data Source=localhost/SQLEXPRESS.Polaris.dbo;Initial Catalog=Polaris;Integrated Security=True;Pooling=False");
protected void Button3_Click(object sender, EventArgs e)
{
con.Open();
string s1 = "insert into Login values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Value + "'";
SqlCommand cmd = new SqlCommand(s1, con);
cmd.ExecuteNonQuery();
}

Categories

Resources