Adding an ImageUrl to an ImageControl - asp.net

I need help how to add an ImageUrl to an ImageControl programmatically. I got this code, but I can't (I don't know how) add path that is stored in database.
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath(".") + "//images//" + str);
string path = "~//images//" + str.ToString();
con.Open();
SqlCommand cmd = new SqlCommand("insert into upload values('" + TextBox1.Text + "','" + path + "')", con);
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "Image uploaded";
SqlDataAdapter da = new SqlDataAdapter("Select img from upload", con);
DataTable dt = new DataTable();
da.Fill(dt);
Image1.ImageUrl =
}
else
{
Label1.Text = "Please select image";
}
}

For that particular scenario, you already have an image filename and path. All you need is Image1.ImageUrl = ResolveUrl("~/images/" + fileName);.
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = FileUpload1.FileName;
string path = string.Format("{0}\\images\\{1}",
HttpRuntime.AppDomainAppPath, fileName);
FileUpload1.PostedFile.SaveAs(path);
/* Save image information to database */
Image1.ImageUrl = ResolveUrl("~/images/" + fileName);
}
else
{
Label1.Text = "Please select image";
}
}
FYI: Your code is prone to SQL Injection attack. Make sure you use Parameterized Query.

Related

How to managed two sql queries in ASP.Net (Visual Studio 2010)

So what I'm trying to do is once I click a button. I want one sql query to insert values to the "Return_Process" Table and another sql query to delete data from the matching loan ID in another table, which is "Loan_Process".
This is the code I have written but its not deleting anything, its inserting the values to the return process but not deleting it from the loan process.
//Global variable declaration
string path;
string sql;
string sql2;
//create a method for database connection
public void connection()
{
//connection string
path = #"Data Source=NATHAN-PC\SQLEXPRESS;Initial Catalog=ASP;Integrated Security=True";
}
protected void Button1_Click(object sender, EventArgs e)
{
{
connection();
SqlConnection con = new SqlConnection(path);
con.Open();
//try
{
sql = "INSERT INTO Return_Process (Return_ID, FIne, Actual_Returned_Date, Loan_ID) VALUES ('" + txtRID.Text + "','" + txtfine.Text + "','" + TextBox1.Text + "','" + txtLID.Text + "')";
sql2 = "Delete FROM Loan_Process WHERE Loan_ID='"+txtLID+"'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
//lblerrormsg.Visible = true;
//lblerrormsg.Text = "Success";
con.Close();
//GridView1.DataBind();
}
//catch (SqlException)
//{
// //lblerrormsg.Visible = true;
// //lblerrormsg.Text = "Invalid";
//}
con.Close();
//GridView1.DataBind();
}
}
}
}
I'm pretty bad at ASP.net, so if someone could tell me what to do to execute both queries at the same time, would greatly appreciate it.
Do something like this:
//your code
sql = "INSERT INTO Return_Process (Return_ID, FIne, Actual_Returned_Date, Loan_ID)"
+ " VALUES (#rid, #fine, #retDate, #lid); " //note ; inside
+ "Delete FROM Loan_Process WHERE Loan_ID=#lid;";
var cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#rid", SqlDbType.Int).Value = Int.Parse(txtRID.Text);
//similar for 3 remaining parameters. Just set correct SqlDbType
con.Open();
cmd.ExecuteNonQuery();
con.Close();

not showing excel data in gridview

when i press button id is btnshow it is not showing uploaded excel file data in gridview , what could be a problem?
protected void btnupload_Click(object sender, EventArgs e)
{
if (System.IO.Path.GetExtension(FileUpload1.FileName) == ".xls" || System.IO.Path.GetExtension(FileUpload1.FileName) == ".xlsx")
{
FileUpload1.SaveAs(Server.MapPath("~/upload/payment.xlsx"));
Label1.Text = "File Uploded";
}
else
{
Label1.Text = "Upload only Excel File";
}
}
protected void btnshow_Click(object sender, EventArgs e)
{
string currpath = Server.MapPath("~/upload/payment.xlsx");
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + currpath + ";Extended Properties=Excel 12.0";
OleDbConnection oledbConn = new OleDbConnection(connString);
try
{
oledbConn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = cmd;
DataSet objDataset1 = new DataSet();
objAdapter1.Fill(objDataset1, "ExcelData");
GridView1.DataSource = objDataset1;
GridView1.DataBind();
}
catch (Exception ex)
{
Label1.Text = "" + ex;
}
finally
{
oledbConn.Close();
}
`
You need to set datasource to a table, not to the dataset.
EDIT : By default datasource will be set to Tables[0]. So your code should work fine. But in the markup you should have AutoGenerateColumns="true" for the GridView:
<asp:GridView ID="GridView1" AutoGenerateColumns="true" runat="server"></asp:GridView>
You can download the project I have used to test your code here.

how can i change the text on button at run time after click on hyperlink

i have two text-boxes a button and a gridview.
Q.1 When user enter details in the text-boxes and press submit button i want to update grid-view accordingly
Q.2 When user hits "Edit" link which is present in the gridview, i would like to change the text of submit button to Update button.
how can i do that thanks in advance
what i have tried yet:
aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid();
string ID = Request.QueryString["ID"];
cmd = new SqlCommand("Select * from UserDetails where ID='" + ID + "'", con);
con.Open();
ad = new SqlDataAdapter(cmd);
dt.Clear();
ad.Fill(dt);
if (dt.Rows.Count > 0)
{
tbid.Text = ID;
TextBox1.Text = dt.Rows[0][1].ToString();
TextBox2.Text = dt.Rows[0][2].ToString();
}
con.Close();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True");
con.Open();
string Name = TextBox1.Text;
string Place = TextBox2.Text;
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "insert into UserDetails(Name,Place) values('" + Name + "','" + Place + "')";
cmd.Parameters.AddWithValue("#Name", TextBox1.Text);
cmd.Parameters.AddWithValue("#Place", TextBox2.Text);
cmd.ExecuteNonQuery();
Label1.Text = "Record Successfully inserted";
}
con.Close();
btnSubmit.Text = "Update";
TextBox1.Text = string.Empty;
TextBox2.Text = string.Empty;
}
private void BindGrid()
{
con.Open();
ad = new SqlDataAdapter("Select * from UserDetails", con);
ad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
Call a Refresh() doesn't help? I'm not sure about ASP.NET, but you have to do it in Forms.
After the user submits new data you can try to call your bindgrid method again, this way it will rebind after the new data is saved. For the edit piece, GridView has an edit template, you can try using that:
http://msdn.microsoft.com/en-us/library/ms972948.aspx

Why session is getting null while inserting the data and getting the data from SQL LITE

I have written a code to insert the data to SQL LITE database as follows
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
count = 0;
Session["x"] = "session value";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string path = Server.MapPath("bin/sampldb.db");
SQLiteConnection conn = new SQLiteConnection("Data Source=" + path + "");
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
string txt="insert into stu values("+TextBox1.Text +",'"+TextBox2.Text+"')";
cmd.CommandType = CommandType.Text;
cmd.CommandText = txt;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Label1.Visible = true;
Label1.Text = "Error:" + ex.Message;
}
}
After inserting while retrieving data Session is getting null I don't know why
protected void Button2_Click(object sender, EventArgs e)
{
if (Session["x"] != null) // Getting Null here
{
Label1.Visible = true;
Label1.Text = Session["x"].ToString();
DataSet m_oDataSet = new DataSet();
string path = Server.MapPath("bin/sampldb.db");
SQLiteConnection conn = new SQLiteConnection("Data Source=" + path + "");
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
string txt = "select * from stu";
cmd.CommandText = txt;
SQLiteDataAdapter adp = new SQLiteDataAdapter();
adp.SelectCommand = cmd;
adp.Fill(m_oDataSet);
GridView1.DataSource = m_oDataSet.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
Label1.Visible = true;
Label1.Text = "Error:" + ex.Message;
}
finally
{
conn.Close();
}
}
}
The same code when tested in Sql server 2008 works fine
protected void BtnSqlInsert_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(cnstr);
con.Open();
SqlCommand cmd = new SqlCommand("Insert into [User] values ('" + TextBox1.Text + "','" + TextBox2.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
}
protected void BtnSqlGet_Click(object sender, EventArgs e)
{
if (Session["x"] != null) //Able to get session here
{
Label1.Visible = true;
Label1.Text = Session["x"].ToString();
}
}
My sql lite path is from Bin folder as shown in image
your app writes to DB (which is in BIN folder). That causes app restart => in-proc session gets lost. You should NOT solve the consequence (by using StateServer mode), you should fix the original reason - move db file into another folder, away from BIN folder.

Accessing Textbox from GridView data cell (ASP.NET)

protected void GridView2_OnCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Reply")
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=myconnectionstring; Integrated Security = true; Connect Timeout = 30; User Instance = True";
con.Open();
string div = "','";
GridViewRow selectedRow = GridView2.Rows[Convert.ToInt32(e.CommandArgument)];
SqlCommand cmd = new SqlCommand("INSERT INTO SellerResponse VALUES ('" +
//THIS LINE IS THE ISSUE
Request.QueryString["ID"] + div + selectedRow.Cells[2].Text + div + DateTime.Now.ToString() + div + selectedRow.Cells[3].Text + ((System.Web.UI.WebControls.TextBox)(FindControl(selectedRow.Cells[1].UniqueID))).Text /*this is the cell that contains the textbox*/+ "');", con);
}
}
Any ideas how to implement this?
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Reply")
{
on = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=myconnectionstring; Integrated Security = true; Connect Timeout = 30; User Instance = True";
con.Open();
string div = "','";
GridViewRow selectedRow = GridView2.Rows[Convert.ToInt32(e.CommandArgument)];
SqlCommand cmd = new SqlCommand("INSERT INTO SellerResponse VALUES ('" +
//THIS LINE IS THE ISSUE
Request.QueryString["ID"] + div + GridView2.Rows[index].Cells[2].Text + div + DateTime.Now.ToString() + div + GridView2.Rows[index].Cells[3].Text + ((System.Web.UI.WebControls.TextBox)(GridView2.Rows[index]Cells[1].FindControl("the name of the text box")).Text /*this is the cell that contains the textbox*/+ "');", con);
}
}
catch (Exception ee)
{
string message = ee.Message;
}
}
Note:1- in aspx :CommandArgument='<%#((GridViewRow)Container).RowIndex%>'
2- use RowCommand event for the grid view.

Resources