How do I take this string and drop it into the select command?
String SqlC = "select * from dbo.FindIt where " + SqlStr;
The object is to populate the SelectCommand:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:M3ConnectionString %>"
SelectCommand = SqlC >
</asp:SqlDataSource>
protected void Page_Load(object sender, EventArgs e)
{
var runx = Request.QueryString.GetValues("run") != null ? Request.QueryString.GetValues("run")[0] : "";
if (runx != "") {
var sqlStr = "RUN= '" + Runx + "'";
var sqlC = "select * from dbo.FindIt where " + sqlStr;
SqlDataSource1.SelectCommand = sqlC;
}
else {
// TODO: Handle this situation.
}
}
Related
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;
}
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 + "')";
I have the following asp.net page which has a button for each row that the repeater creates:
<asp:Repeater runat="server" ID="rptContent" OnItemCommand="btnGeneratePDF_Click">
<HeaderTemplate>
<table border="0" style="width: 95%;">
<tr>
<td style="width: 25%;">Name</td>
<td style="width: 25%;">Last Four SSN #</td>
<td style="width: 25%;">PDF Generator</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("name").ToString() %></td>
<td><%# Eval("ssn3").ToString() %></td>
<td><asp:Button ID="btnGeneratePDF" runat="server" Text="Generate PDF" CommandArgument='<%# Eval("name").ToString() + ", " + Eval("ssn3").ToString() %>' /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
My code behind looks like this:
protected void btnGeneratePDF_Click(object sender, CommandEventArgs e)
{
string[] ar = e.CommandArgument.ToString().Split(',');
this.writeData(ar[0], ar[1]);
}
public void writeData(string k, string c)
{
Conn = new SqlConnection(cString);
Conn.Open();
//MessageBox.Show(k);
//MessageBox.Show(c);
nameE = txtName.Text;
var pdfPath = Path.Combine(Server.MapPath("~/PDFTemplates/fw9.pdf"));
// Get the form fields for this PDF and fill them in!
var formFieldMap = PDFHelper.GetFormFieldNames(pdfPath);
formFieldMap["topmostSubform[0].Page1[0].f1_01_0_[0]"] = k;
//sqlCode = "SELECT * FROM [db].[dbo].[TablePDFTest] WHERE [name] = '" + nameE + "'";
sqlCode = "SELECT * FROM [db].[dbo].[TablePDFTest] WHERE [name] = '" + k + "' AND [ssn3] = '" + c + "'";
//MessageBox.Show("" + sqlCode.ToString());
using (SqlCommand command = new SqlCommand(sqlCode, Conn))
{
command.CommandType = CommandType.Text;
using (reader = command.ExecuteReader())
{
if (reader.HasRows)
{
if (reader.Read())
{
formFieldMap["topmostSubform[0].Page1[0].f1_02_0_[0]"] = reader.GetValue(1).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_04_0_[0]"] = reader.GetValue(2).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_05_0_[0]"] = reader.GetValue(3).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_07_0_[0]"] = reader.GetValue(4).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField1[0]"] = reader.GetValue(5).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[0]"] = reader.GetValue(6).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[1]"] = reader.GetValue(7).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[2]"] = reader.GetValue(8).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[3]"] = reader.GetValue(9).ToString();
}
}
}
}
// Requester's name and address (hard-coded)
formFieldMap["topmostSubform[0].Page1[0].f1_06_0_[0]"] = "Medical Group\n27 West Ave\nPurchase, NY 10577";
var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);
PDFHelper.ReturnPDF(pdfContents, "Completed-W9.pdf");
}
If my
sqlCode is sqlCode = "SELECT * FROM [DSPCONTENT01].[dbo].[TablePDFTest] WHERE [name] = '" + k + "'"; //AND [ssn3] = '" + c + "'"; it works fine for the formFieldMap
but if my
sqlCode is sqlCode = "SELECT * FROM [DSPCONTENT01].[dbo].[TablePDFTest] WHERE [name] = '" + k + "' AND [ssn3] = '" + c + "'"; the formFieldMap doesn't work correctly.
This is an example of what the repeater displays:
How can I fix it?
UPDATE:
I did a test with MessageBox to display the value using the query with both variable:
public void writeData(string k, string c)
{
Conn = new SqlConnection(cString);
Conn.Open();
//MessageBox.Show(k);
//MessageBox.Show(c);
nameE = txtName.Text;
var pdfPath = Path.Combine(Server.MapPath("~/PDFTemplates/fw9.pdf"));
// Get the form fields for this PDF and fill them in!
var formFieldMap = PDFHelper.GetFormFieldNames(pdfPath);
formFieldMap["topmostSubform[0].Page1[0].f1_01_0_[0]"] = k;
sqlCode = "SELECT * FROM [db].[dbo].[TablePDFTest] WHERE [name] = '" + k + "' AND [ssn3] = '" + c + "'";
//MessageBox.Show("" + sqlCode.ToString());
using (SqlCommand command = new SqlCommand(sqlCode, Conn))
{
command.CommandType = CommandType.Text;
using (reader = command.ExecuteReader())
{
if (reader.HasRows)
{
if (reader.Read())
{
MessageBox.Show(reader.GetValue(1).ToString());
MessageBox.Show(reader.GetValue(2).ToString());
MessageBox.Show(reader.GetValue(3).ToString());
MessageBox.Show(reader.GetValue(4).ToString());
MessageBox.Show(reader.GetValue(5).ToString());
MessageBox.Show(reader.GetValue(6).ToString());
MessageBox.Show(reader.GetValue(7).ToString());
MessageBox.Show(reader.GetValue(8).ToString());
MessageBox.Show(reader.GetValue(9).ToString());
/*formFieldMap["topmostSubform[0].Page1[0].f1_02_0_[0]"] = reader.GetValue(1).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_04_0_[0]"] = reader.GetValue(2).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_05_0_[0]"] = reader.GetValue(3).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_07_0_[0]"] = reader.GetValue(4).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField1[0]"] = reader.GetValue(5).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[0]"] = reader.GetValue(6).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[1]"] = reader.GetValue(7).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[2]"] = reader.GetValue(8).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[3]"] = reader.GetValue(9).ToString();*/
}
}
}
}
// Requester's name and address (hard-coded)
/*formFieldMap["topmostSubform[0].Page1[0].f1_06_0_[0]"] = "Medical Group\n27 West Ave\nPurchase, NY 10577";
var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);
PDFHelper.ReturnPDF(pdfContents, "Completed-W9.pdf");*/
}
The messagebox isn't displayed anymore instead when I click on the button, nothing happens.
What is the data type of ssn3 in SQL? You are passing c as a string literal. That is something to look at. Maybe just try removing the single quotes around your value for c (if it is integer for instance).
Also, what happens when you type the query into a query analyzer with some test data for the WHERE clause? Do you know if there SHOULD be rows matching both values?
May be you should use some ORM system, that will make your database life easier. It will also help you to avoid some sql-injections, that you've already made in your code.
Try to google Fluent NHibernate
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 trying to validate three textboxes, all of them are just text field. They are all connected to a database with sqlserver.
Now I want to know how to stop the form from adding empty records into my database when its still empty. I have some Javascript validation, which tells the user that the field is empty, but after you click okay for the message box, the page refreshes and an empty record is added.
If anyone could help me with a bit of code that'd be great.
My javascript looks like this:
function myAddFunction() {
var a = document.forms["form1"]["txtFirstName"].value;
var b = document.forms["form1"]["txtLastName"].value;
var c = document.forms["form1"]["txtvercode"].value;
if (a == null || a == "") {
alert("Please Enter a value");
return false;
}
if (b == null || b == "") {
alert("Please Enter a value");
return false;
}
if (c == null || c == "") {
alert("Please Enter a value");
return false;
}
else {
alert("The Member has been added!");
return true;
}
}
My Default.aspx.cs file looks like this:
protected void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(
#"Data Source=(LocalDB)\v11.0; AttachDbFilename='|DataDirectory|\employees.mdf';
Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO membership (FirstName, LastName, MembershipClass, VerificationCode) VALUES ('" + txtFirstName.Text + "', '" + txtLastName.Text + "', '" + dropmemberclass.Text + "', '" + txtvercode.Text + "')", conn);
cmd.ExecuteNonQuery();
txtFirstName.Text = "";
txtLastName.Text = "";
txtvercode.Text = "";
txtMemID.Text = "";
txtmemdelete.Text = "";
lblMemID.Text = "";
lblMemIDSearch.Text = "";
}
You can add a RequiredFieldValidator to each TextBox:
<asp:RequiredFieldValidator id="RequiredFieldValidator2"
ControlToValidate="txtFirstName"
Text="First name is a required field"
ForeColor="red"
runat=server>
This validates data both client side and server side so you don't need any of that Javascript code.
replace the code with this:
SqlConnection conn = new SqlConnection(
if(txtFirstName.Text != "" && txtLastName.Text != "" && txtvercode.Text = "")//And so on...
{
#"Data Source=(LocalDB)\v11.0; AttachDbFilename='|DataDirectory|\employees.mdf';
Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO membership (FirstName, LastName, MembershipClass, VerificationCode) VALUES ('" + txtFirstName.Text + "', '" + txtLastName.Text + "', '" + dropmemberclass.Text + "', '" + txtvercode.Text + "')", conn);
cmd.ExecuteNonQuery();
txtFirstName.Text = "";
txtLastName.Text = "";
txtvercode.Text = "";
txtMemID.Text = "";
txtmemdelete.Text = "";
lblMemID.Text = "";
lblMemIDSearch.Text = "";
}
}
Add more to the condition i added...
you can add any keys like primary key to the columns so it will not accept null value and add requiredfieldvalidator to your text boxes
Check this
<asp:CustomValidator ID="myCustValidator" runat="server" ControlToValidate="txtFirstName" OnServerValidate="ServerFirstNameValid"></asp:CustomValidator>
protected void ServerFirstNameValid(object source, ServerValidateEventArgs args)
{
args.IsValid = !String.IsNullOrEmpty(txtFirstName.Text.Trim());
if (!args.IsValid)
myCustValidator.ErrorMessage="First Name should not be Empty";
}