I have the database updating with the UserName of the person who uploaded a file and am trying to retrieve only the files the current user uploaded, to display in the gridview.
The page displays the current user name and when that person uploads a file everything is fine. Though when that user hits the search button, all records show up and I get the error:
Error:Invalid column name 'test'
protected void ButtonSearch_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
try
{
string UN = Session["New"].ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlDataReader reader;
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM UserUpload WHERE UserName = #un";
command.Parameters.Add(new SqlParameter("#un", UN));
command.Connection = conn;
conn.Open();
reader = command.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}
Change this line
string UserSearch = "SELECT * FROM UserUpload WHERE UserName =" + UN;
to
string UserSearch = string.Format("SELECT * FROM UserUpload WHERE UserName ='{0}'",UN);
you want to match to username as string strings are being wrapped in '' in SQL
If you would be matching by number it would work fine as numbers do not have this requirement.
UPDATE to UPDATE:
Change to something like this (untested)
SqlCommand com = new SqlCommand(UserSearch, conn);
{ DataSet ds = com.ExecuteReader();
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
conn.Close();
}
You would benefit from reading this
Use Parameters instead of assinging the Value to the query string
protected void ButtonSearch_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
try
{
string UN = Session["New"].ToString(); ;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string UserSearch = "SELECT * FROM UserUpload WHERE UserName = #un";
SqlCommand com = new SqlCommand(UserSearch, conn);
com.Parameters.Add(new SqlParameter("#un", UN));
com.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}
Related
i have the following code below and what im trying to do is on the comboBox there is "ID" from my database and this ID represents every survey detail that Admin used to create so when the user goes to view the survey they click on the survey number in comboBox and the labels will change according to the database. I tried it with the below code but unfortunatley all it seems to do is grab a random one, if someone could help that would be amazing. It doesnt have to be like below, just as long as it works,
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con.Open();
string query = "SELECT * FROM tbl_newsurvey ";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = query;
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string name = reader["txtname"].ToString();
lblname.Text = name;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
You can try this to search data from database using Combobox
I use parameterized query to avoid SQL Injection
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con.Open();
string query = "SELECT * FROM tbl_newsurvey WHERE [ColumnName] = #ComboBoxValue";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#ComboBoxValue", comboBox1.SelectedIndex.ToString())
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read() == true)
{
string name = reader["txtname"].ToString();
lblname.Text = name;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
I have an update panel with some gridviews being populated on postback as well as some textboxes that are populated through code and an SqlDataReader on _SelectedIndexChanged. Everything is working except for the two date textboxes that are set to TextMode=Date are not populating. I'm sure it's some formatting issue and I've searched and tried a few different things to no avail..... Thanks in advance !
P.s. edited out connection string
public void ddlSO_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = "";
String strQuery = "select strServiceOrderNo, strCustomerNo, strCustomerName, strCustomerAddress1, strCustomerAddress2, strCustomerAddress3, strServiceRequestDate, strServiceOrderDate, intStatusCodeID, intRepID from TServiceOrders where" +
" intServiceOrderID = #intServiceOrderID";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#intServiceOrderID", ddlSO.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
txtCUSTNO.Text = sdr["strCustomerNo"].ToString();
txtSONO.Text = sdr["strServiceOrderNo"].ToString();
txtAddress1.Text = sdr["strCustomerAddress1"].ToString();
txtAddress2.Text = sdr["strCustomerAddress2"].ToString();
txtAddress3.Text = sdr["strCustomerAddress3"].ToString();
txtDateCreated.Text = sdr["strServiceOrderDate"].ToString() ;
txtDateDue.Text = sdr["strServiceRequestDate"].ToString();
txtCustName.Text = sdr["strCustomerName"].ToString();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
I am trying to retrieve data from a Database and show them on a form; but my code isn't working... I've got no errors, and logically it seems to work (to me) so I cannot figure out where I have gone wrong. That's where I need your help!
private void tableListBox_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE Default_Name = '" + tableListBox.SelectedValue + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader Reader;
try
{
con.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
textBox1.Text = Reader.GetValue(2).ToString();
comboBox1.Text = Reader.GetValue(3).ToString();
comboBox3.Text = Reader.GetValue(4).ToString();
textBox2.Text = Reader.GetValue(6).ToString();
comboBox2.Text = Reader.GetValue(7).ToString();
comboBox4.Text = Reader.GetValue(8).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
The 'tableListBox' is populated with all the values in column 'Default_Name'. I want it so that when the 'Default_Name' is selected from the list box it shows the values, in textboxes and comboboxes, that correspond with that row in the Database.
Any and all help would be appreciated. Thanks.
I'm going to start by changing your design a bit and suggest that perhaps you look at using a datatable and then just retrieving the rows from the datatable.
private void tableListBox_SelectedIndexChanged(object sender, EventArgs e)
{
private DataTable dataTable;
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE Default_Name = '" + tableListBox.SelectedValue + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
foreach(DataRow row in dataTable.Rows)
{
textBox1.Text = row[2].ToString();
comboBox1.Text = row[3].ToString();
comboBox3.Text = row[4].ToString();
textBox2.Text = row[6].ToString();
comboBox2.Text = row[7].ToString();
comboBox4.Text = row[8].ToString();
}
da.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
I generally find that DataTables are more reliable than looping through the actual reader. Ofcourse this assumes that there is data being returned. Also try changing your select statement to this
string Query = "SELECT * FROM [Table]"
If that works, then the problem could be
There is no default name of the specified value or
tableListBox.SelectedValue is not returning any value, in which case, have a look at your listbox selected value
Thanks to Takarii for helping. I figured out who to make it work.
private void tableListBox_SelectedValueChanged(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE ID = '" + tableListBox.SelectedIndex.ToString() + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader Reader;
try
{
con.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
textBox1.Text = Reader.GetValue(2).ToString();
comboBox1.Text = Reader.GetValue(3).ToString();
comboBox3.Text = Reader.GetValue(4).ToString();
textBox2.Text = Reader.GetValue(6).ToString();
comboBox2.Text = Reader.GetValue(7).ToString();
comboBox4.Text = Reader.GetValue(8).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
First I changed the void to 'SelectedValueChanged' and then I changed the 'WHERE' in the connection Query to the Row Index associated with the selected Value.
Thanks for everyone's help!
protected void Button1_Click1(object sender, EventArgs e) {
try {
conn.Open();
string idquery = "select top 1 pid from post order by pid desc ";
cmd = new SqlCommand(idquery, conn);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
string p1id = (reader["pid"].ToString());
int pid = Convert.ToInt32(p1id);
TextBox3.Text = (reader["pid"].ToString());
conn.Close();
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
string insertQuery = "insert into post (pid ,pidtype ,title ,question,creationdate) values (#pid,#ptype,#title,#question,#cdate)";
com = new SqlCommand(insertQuery, conn1);
DateTime now = DateTime.Now;
++pid;
com.Parameters.AddWithValue("#pid", pid);
com.Parameters.AddWithValue("#ptype", 1);
com.Parameters.AddWithValue("#title", TextBox2.Text);
com.Parameters.AddWithValue("#question", TextArea1.Text);
com.Parameters.AddWithValue("#cdate", now);
Response.Write("successfull");
Response.Redirect("questions.aspx");
conn1.Close();
} catch (Exception ex) {
Response.Write("error" + ex.ToString());
}
}
this is the code i've written..its not giving any error or exception...bt data is not getting inserted into database
You need to call ExecteNonQuery, afte adding all the parameters:-
com.ExecteNonQuery();
How would I stop the repeating of data in my DropDownLists? I couldn't find any good examples of DropDownlists with non repeating values from sql? I tried to make the select statement say Distinct.
Here is my code I am using:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = (string)Session["name"];
if (!IsPostBack)
{
DropDownList1.AppendDataBoundItems = true;
DropDownList2.AppendDataBoundItems = true;
DropDownList3.AppendDataBoundItems = true;
DropDownList4.AppendDataBoundItems = true;
String strConnString = ConfigurationManager
.ConnectionStrings["connectionString"].ConnectionString;
String strQuery = "select distinct * from dbo.Vehiclemain WHERE ISENABLED = 'YES'";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "Year";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
con.Close();
con.Open();
DropDownList2.DataSource = cmd.ExecuteReader();
DropDownList2.DataTextField = "Make";
DropDownList2.DataValueField = "ID";
DropDownList2.DataBind();
con.Close();
con.Open();
DropDownList3.DataSource = cmd.ExecuteReader();
DropDownList3.DataTextField = "Model";
DropDownList3.DataValueField = "ID";
DropDownList3.DataBind();
con.Close();
con.Open();
DropDownList4.DataSource = cmd.ExecuteReader();
DropDownList4.DataTextField = "Submodel";
DropDownList4.DataValueField = "ID";
DropDownList4.DataBind();
con.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
It looks like you want to change the drop downs based on the first drop down.
If that's the case, you would want to make the drop down an autopost back as well.
Everytime someone changes the year, a make will be filled based on the year.
Everytime someone changes the make, a model will be filled based on the make .
Everytime someone changes the model , a submodel will be filled based on the model .
The sQL query will be scaffolded as we build the information...
The code below has not been tested.
<asp:DropDownList ID="ddlYearObj" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlObj_SelectedIndexChanged" ></asp:DropDownList>
<asp:DropDownList ID="ddlMakeObj" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlMakeObj_SelectedIndexChanged" Visible="false"></asp:DropDownList>
<asp:DropDownList ID="ddlModelObj" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlModelObj_SelectedIndexChanged" Visible="false"></asp:DropDownList>
<asp:DropDownList ID="ddlSubmodelObj" runat="server" Visible="false"></asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = (string)Session["name"];
if (!IsPostBack)
{
String strConnString = ConfigurationManager
.ConnectionStrings["connectionString"].ConnectionString;
String strQuery = "select distinct Year from dbo.Vehiclemain WHERE ISENABLED = 'YES'";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ddlYearObj.DataSource = cmd.ExecuteReader();
ddlYearObj.DataTextField = "Year";
ddlYearObj.DataValueField = "Year";
ddlYearObj.DataBind();
con.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
//Visible!? -- All invisible until something is chosen
ddlMakeObj.Visible = false;
ddlModelObj.Visible = false;
ddlSubmodelObj.Visible = false;
}
protected void ddlYearObj_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = ConfigurationManager
.ConnectionStrings["connectionString"].ConnectionString;
String strQuery = "select distinct Make from dbo.Vehiclemain WHERE ISENABLED = 'YES' AND YEAR = "+ ddlYearObj.Value;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ddlMakeObj.DataSource = cmd.ExecuteReader();
ddlMakeObj.DataTextField = "Make";
ddlMakeObj.DataValueField = "Make";
ddlMakeObj.DataBind();
con.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
//Visible!
ddlMakeObj.Visible = true;
ddlModelObj.Visible = false;
ddlSubmodelObj.Visible = false;
}
protected void ddlMakeObj_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = ConfigurationManager
.ConnectionStrings["connectionString"].ConnectionString;
String strQuery = "select distinct modelfrom dbo.Vehiclemain WHERE ISENABLED = 'YES' AND YEAR = "+ ddlYearObj.Value;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ddlModelObj.DataSource = cmd.ExecuteReader();
ddlModelObj.DataTextField = "Model";
ddlModelObj.DataValueField = "Model";
ddlModelObj.DataBind();
con.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
//Visible!
ddlMakeObj.Visible = true;
ddlModelObj.Visible = true;
ddlSubmodelObj.Visible = false;
}
protected void ddlModelObj_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = ConfigurationManager
.ConnectionStrings["connectionString"].ConnectionString;
String strQuery = "select distinct Submodelfrom dbo.Vehiclemain WHERE ISENABLED = 'YES' AND YEAR = "+ ddlYearObj.Value + " AND Model = '" + ddlModelObj.Value + "'";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ddlSubmodelObj.DataSource = cmd.ExecuteReader();
ddlSubmodelObj.DataTextField = "Submodel";
ddlSubmodelObj.DataValueField = "ID";
ddlSubmodelObj.DataBind();
con.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
//Visible!
ddlMakeObj.Visible = true;
ddlModelObj.Visible = false;
ddlSubmodelObj.Visible = true;
}
You are using single query to populate all your dropdowns. Try creating 4 select statments with applying distinct to appropriate column. for ex Make dropdown would have distinct Make in the query.