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;
}
Related
I receive this error from my code below. Why am I getting an exception saying that the "value returned null" when my intellisense is telling me that the variable is what it is supposed to be when I hover the variable at the breakpoint.
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Windows.Forms.DataGridViewCell.Value.get returned null.
private void button1_Click(object sender, EventArgs e)
{
string StrQuery;
DataTable ReturnInfoDataTable = new DataTable();
using (var connection = new SqlConnection("Server=;Database=;Trusted_Connection=True;"))
{
connection.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string enteredCustomerNum = dataGridView1.Rows[i].Cells["Customer_Number"].Value.ToString();
string enteredInvoiceNum = dataGridView1.Rows[i].Cells["Invoice_Number"].Value.ToString();
string enteredRefundNum = dataGridView1.Rows[i].Cells["Refund_Number"].Value.ToString();
string enteredCheckNum = dataGridView1.Rows[i].Cells["Check_Number"].Value.ToString();
StrQuery = #"SELECT '" + enteredCheckNum + "' AS Check_Number, [Company_Num],[RHH_INV_NUMBER],[RHH_CUST_NUMBER],[RHH_RETURN_NUMBER],[RHH_CR_REFUND_NUM],[RHH_ENTERED_DATE],[RHH_DATE_POSTED],[RHH_DATE_RESOLVED] ,[TOTAL_AMOUNT] FROM[History_Warehouse].[dbo].[tbl_Return_Header] WHERE[RHH_CUST_NUMBER] = '" + enteredCustomerNum + "' AND[RHH_CR_REFUND_NUM] = '"+ enteredRefundNum + "' AND[RHH_RETURN_NUMBER] = '" + enteredInvoiceNum + "'";
using (var command = new SqlCommand(StrQuery, connection))
{
ReturnInfoDataTable.Load(command.ExecuteReader());
}
}
}
Why do I get a null exception when the value isn't null, and how can I fix it.
Edit: I know this is getting downvotes for a bad question, but I believe I have some information to share that will be helpful..
Basically what was happening is that the DataGridView object has a property called AllowUserTOAddRows and this auto adds a hidden row.. To fix this i simply added dataGridView1.AllowUserToAddRows = false; to the beginning of my onclick event and this solves the issue..
private void button1_Click(object sender, EventArgs e)
{
string StrQuery;
DataTable ReturnInfoDataTable = new DataTable();
dataGridView1.AllowUserToAddRows = false;
using (var connection = new SqlConnection("Server=;Database=;Trusted_Connection=True;"))
{
connection.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string enteredCustomerNum = dataGridView1.Rows[i].Cells["Customer_Number"].Value.ToString();
string enteredInvoiceNum = dataGridView1.Rows[i].Cells["Invoice_Number"].Value.ToString();
string enteredRefundNum = dataGridView1.Rows[i].Cells["Refund_Number"].Value.ToString();
string enteredCheckNum = dataGridView1.Rows[i].Cells["Check_Number"].Value.ToString();
StrQuery = #"SELECT '" + enteredCheckNum + "' AS Check_Number, [Company_Num],[RHH_INV_NUMBER],[RHH_CUST_NUMBER],[RHH_RETURN_NUMBER],[RHH_CR_REFUND_NUM],[RHH_ENTERED_DATE],[RHH_DATE_POSTED],[RHH_DATE_RESOLVED] ,[TOTAL_AMOUNT] FROM[History_Warehouse].[dbo].[tbl_Return_Header] WHERE[RHH_CUST_NUMBER] = '" + enteredCustomerNum + "' AND[RHH_CR_REFUND_NUM] = '"+ enteredRefundNum + "' AND[RHH_RETURN_NUMBER] = '" + enteredInvoiceNum + "'";
using (var command = new SqlCommand(StrQuery, connection))
{
ReturnInfoDataTable.Load(command.ExecuteReader());
}
}
}
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
}
}
My Problem as follows;
Last row of datagridview is always Focused, so when I click the btnSave of toolStripButton, I can not save the last row data to the database. How should I solve this problem? I know if I use the Button Control, I can solve this problem. But I want to know more:
private void btnSave_Click(object sender, EventArgs e)
{
dgvHead.EndEdit();
dgvHead.RefreshEdit();
dgvHead.Refresh();
dgvHead.Update();
dgvHead.LostFocus += new EventHandler(dataGridView1_LostFocus);
//dgvHead.ClearSelection();
//int id = 0;
//保存到数据库之前先判断一下主表是否有重复记录
string fno = txtfNo.Text.Trim();
string fname = txtPname.Text.Trim();
int orderqty = Convert.ToInt32(txtOrderQty.Text);
double orderc = Convert.ToDouble(txtOrderCoefficient.Text);
Image pic = pbchef.Image;
//主表的修改
string sql1 = "select count(1) from desProductAttach where fno='" + fno + "' and fno!='" + args["pNo"].ToString() + "' and fname='" + fname + "' and orderqty=" + orderqty + " and orderCoefficient=" + orderc + "";
int count = Convert.ToInt32(SqlHelp.GetValue(CommandType.Text, sql1));
if (count != 0)
{
MessageBox.Show("数据库中已经存在重复记录,请修改后重新录入!");
return;
}
string sql2 = #"update desProductAttach set fno='" + fno + "',fname='" + fname + "',orderqty=" + orderqty + ",orderCoefficient=" + orderc + " where id="+id+"";
SqlHelp.ExecuteNonQuery(CommandType.Text,sql2);
//子表的更新(通过数据源更新)
if (ds1.HasChanges())
{
SqlCommandBuilder cb = new SqlCommandBuilder(sda1);
sda1.Update(ds1.Tables[0]);
ds1.AcceptChanges();
// dgvHead.Update();
MessageBox.Show("保存成功");
// ischange = false;
}
}
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.
I am designing a Window based application in C# using VS2010 and SqlServer2008-r2. I am
using a service Based Database(.mdf),in it there is a table having four fields, if i Store
data in the table and close the application and re-run the application the data gets Lost.
Why so and how to get rid of it.
I am Using Following routine for saving
private void Save(object sender, EventArgs e)
{
Program.connection.Close();
bool k = srchpreventry();
try
{
if (k)
{
string query = " update orderform set Enrolment_Expected = " + textBox2.Text + ", Stock_on_Hand=" + textBox3.Text + ", Number_Required = "+ textBox4.Text + " where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
cmd.ExecuteNonQuery();
Program.connection.Close();
}
else
{
// Program.connection.Open();
string query = "insert into orderform(Name,Enrolment_Expected,Stock_on_Hand,Number_Required) values('" + textBox1.Text + "', '" + textBox2.Text + "', ' " + textBox3.Text + "',' " + textBox4.Text + "')";
SqlCommand cmd = new SqlCommand(query, Program.connection);
cmd.ExecuteNonQuery();
Program.connection.Close();
}
}
catch (Exception ae)
{
string str = ae.ToString();
MessageBox.Show(str);
}
finally
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox1.Enabled = false;
textBox2.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
Program.connection.Close();
}
}
public bool srchpreventry()
{
Program.connection.Open();
string query = " Select name from orderform where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read() == true)
{
dtr.Close();
return true;
}
else
{
dtr.Close();
return false;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Program.connection.Close();
Program.connection.Open();
string query = " Select * from orderform where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read() == true)
{
textBox2.Text = dtr[1].ToString();
textBox3.Text = dtr[2].ToString();//GetString(2);
textBox4.Text = dtr[3].ToString();
}
else
{
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
public static SqlConnection connection = null;
static string appath = Library_Records.Program.app_path;
string connectionstring = string.Format(#"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;User Instance=True", appath);
static string dbfiles = null;
internal static string app_path
{
get { return dbfiles = "|Datadirectory|\\records.mdf"; }
}
/*******************datagrid code********************/
Program.connection.Open();
string query = "select * from orderform";
SqlDataAdapter MyDA = new SqlDataAdapter();
MyDA.SelectCommand = new SqlCommand(query, Program.connection);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
Check to see if you can increase the characters allowed in the column for example nvarchar(max) cause now it could be nvarchar(200) - this is just an example
In Visual Studio?
You are not by chane having VIsual Studio load the same empty database again every time you start debug?
and close the application and re-run the application the data gets Lost.
Either someone ignores errors that get thrown on insert, does not commit a transaction or tvisal studio just ocpies the same rdatabase template into the directory every time you start.
I strongly (emphasis on strongly) suggest that you start using stored procedures (either in code or in the database), but besides that.. you don't start a transaction or something similar?
Or post the Program.Connection class code into the question.