Pass NavigateUrl Id to next page Sql statement - asp.net

I am coding "List all Product" page in asp.net. I did the connection from the DB to ViewList. Now I have to make the products clickable. What I have coded so far in the asp part is , as it follows:
<div class="image">
<asp:HyperLink ID="HyperLinkSaleDesign" runat="server" NavigateUrl='<%# Eval("ID" , "~/EN/ViewTemplate.aspx?id={0}") %>'>
<asp:Image ID="ImageSaleDesign" runat="server" Width="247" Height="150" ImageUrl='<%# Eval("thumb") %>' />
</asp:HyperLink>
</div>
The navigation URL works and I can see the selected "?id={0}".
However I cannot pass the data correctly , so the SQL query on the next page does not work.
I am not sure how to pass this value to the Select statement. Here is what I have done so far:
String IDquery = ("QueryStringParameter[ID]"); // doesn't work
try
{
string ConnectionString = WebConfigurationManager.ConnectionStrings["Twebconfig"].ConnectionString;
SqlConnection viewTemplate = new SqlConnection(ConnectionString);
SqlDataAdapter viewTemplateSet = new SqlDataAdapter("SELECT " +
" * FROM saleDesigns WHERE ID = #IDquery", viewTemplate); // doesn't seem to see the variable
Data Binding - etc. etc. etc
}
catch (Exception err)
{
mylabel.Text = "Invalid " + err.Message;
}
I am open to any suggestions.
Thank you.

I'm a bit confused by your code, but it looks like you just need to retrieve the id from QueryString and build a SQL query with it, right?
Is this what you're trying to do?:
int id = int.Parse(Request.QueryString["id"]);
You can put the query together using the ID from QueryString, you can do something like this:
//just an example - should be parameterized to avoid injection
string query = String.Format("SELECT ID, Col1, Col2 FROM Table1 WHERE ID={0}", Request.QueryString["ID"]);

This is the way it works for me:
int v = 0;
try
{
int v = int.Parse(Request.QueryString["id"]);
}
catch (Exception e)
{}
if (v > 0)
{
try
{
string ConnectionString = WebConfigurationManager.ConnectionStrings["connstring"].ConnectionString;
SqlConnection conn = new SqlConnection(ConnectionString);//explisionremoteEntities
string query = String.Format("SELECT * FROM table WHERE ID={0}", Request.QueryString["ID"]);
SqlDataAdapter viewTemplateSet = new SqlDataAdapter(query, conn);
}
catch
{
//code in here
}
}

Related

dropdownList doesn't displays selected value

I am new at asp.net. I have a dropdownList which displays all categories for a specific article. The problem is that when I want to edit an article it doesn't displays the value that exists as default selected in dropdownList.
protected void datalist2_OnItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.EditItem)
{
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection con = new SqlConnection(connection);
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id";
drpdKategoria.DataTextField = "emertimi";
drpdKategoria.DataBind();
drpdKategoria.SelectedValue = drpdKategoria.Items.FindByText(Qry).Value;
//drpdKategoria.Items.FindByValue(string val).Selected = true;
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
}
EditArtikull.aspx
<asp:Label ID="Label5" runat="server" style="font-weight: 700">Kategoria</asp:Label>
<fieldset>
<asp:DropDownList ID="drpdKategoria" runat="server" AutoPostBack="false"></asp:DropDownList>
</fieldset>
<br/>
ERROR:SystemNullReference Exception {"Object reference not set to an instance of an object."}
This line probably isn't going to find anything:
drpdKategoria.Items.FindByText(Qry)
Since Qry is a SQL statement:
string Qry = "select * from kategoria";
And I'm assuming that the display values in your DropDownList aren't SQL queries. Thus, when you call .Value on that first line, you're trying to de-reference something that isn't found (which is null), hence the error.
What item are you actually trying to find? If you want to select a default item, you need to be able to identify that item in some way. In your data that would be either by a known id value or a known emertimi value. For example, if you have a known emertimi value, it would be:
drpdKategoria.SelectedValue = drpdKategoria.Items.FindByText("some known value").Value
To make this a little more robust, you probably want to add some null checking. Something like this:
var defaultValue = drpdKategoria.Items.FindByText("some known value");
if (defaultValue != null)
drpdKategoria.SelectedValue = defaultValue.Value

Update database in asp.net not working

i have in asp.net a few textboxes and i wish to update my database with the values that they encapsulate .
The problem is that it doesn't work and although it doesn't work, the syntax seems correct and there are no errors present . Here is my linkbutton :
<asp:linkbutton id="clickOnSave" runat="server"
onclick="Save_Click" Text="Save Profile" />
and my update function
protected void Save_Click(object sender, EventArgs e)
{
SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "DataSource=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\alex\\Documents\\seeubook_db.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
con.Open();
String commandString = "UPDATE users SET last_name='" + Text4.Text.Trim() + "' , first_name='" + Textbox1.Text.Trim() + "' , about_me='" + Textbox5.Text.Trim() + "' , where_i_live='" + Textbox2.Text.Trim() + "' , where_i_was_born='" + Textbox3.Text.Trim() + "' , work_place='" + Textbox4.Text.Trim() + "' WHERE email='" + Session["user"] + "'";
SqlCommand sqlCmd = new SqlCommand(commandString, con);
sqlCmd.ExecuteNonQuery();
con.Close();
}
I'm always a bit weary about the User Instance=true in a connection string..... at times, it tends to create a new MDF file "on the fly" and when you update that MDF, then your changes might be just "gone" one your app has completed running.... See MSDN docs on User Instances.
I would suggest that you:
attach your MDF file to SQL Server Express on your machine, using SQL Server Express Management Studio
then use a server-based approach to your SQL Server Express database rather than attaching a file...
In that case, your database connection string would then look something like:
server=.\\SQLEXPRESS;database=YourDatabaseName;Integrated Security=SSPI;
And while you're at it, I would also recommend to:
wrap your SqlConnection and SqlCommand into using blocks to ensure proper disposal
open your connection as late as possible
use a parametrized query instead of concatenating together your SQL command - doing so is a wide open door for SQL injection attacks!
So your code would look something like this:
string connStr = "server=.\\SQLEXPRESS;database=YourDatabaseName;Integrated Security=SSPI;";
string cmdStmt = "UPDATE dbo.Users SET last_name = #lastName, " +
"first_name = #firstName, about_me = #aboutMe, where_i_live = #whereILive, " +
"where_i_was_born = #whereIWasBorn, work_place = #workPlace " +
"WHERE email = #userEMail";
using(SqlConnection sqlCon = new SqlConnection(connStr))
using(SqlCommand sqlCmd = new SqlCommand(cmdStmt, sqlCon))
{
// define parameters
sqlCmd.Parameters.Add("#lastName", SqlDbType.VarChar, 50);
sqlCmd.Parameters["#lastName"].Value = Text4.Text.Trim();
// and so on for all the parameters
sqlCon.Open();
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
}
Debug! Look your LinkButton Click Event really go into Save_Click function. And then check 'sqlCmd.ExecuteNonQuery();' return result.
You need to write your code for filling Textbox's at page load as below :
public page_load()
{
if(!ispostBack)
{
// Write code to fill controls first time
}
}

Gridview filtering using textbox in asp.net

i want to know as how to search or filter records in a gridview dynamically based on the character(s) entered on a textbox. What is the best way to achieve this? Any sample codes or examples will be really helpful.
The trick here is to make databind only when the text change on the search box, but you must always set the datasource select command code. So you add a text box, and a button that say, submit, and you have the following:
OnPageLoad ->
if(SearchContron.Text.Length > 0)
SqlDataSource1.SelectCommand = "SELECT * FROM TABLE WHERE Desc LIKE N'%" + SearchContron.Text +"%'"
else
SqlDataSource1.SelectCommand = "SELECT * FROM TABLE "
and
OnSubmitButtonClick -> GridView.DataBind()
If you do it other way, the paging and editing and other commands will fail. You can also make it more advanced if you get the text from the text box and break it in many words and search each one as separate on the same sql command.
Its simple,
Look here for a basic tutorial on adding Ajax control to page.
1) Add the text box as well as the grid view into same update panel
2) In the text box's key press event, you can set the data source of gird and invoke databind command.
Note that when the key press will be fired, it will cause the complete page life cycle to be executed at server side. Hence, you will have to check whether the post back is async or not in your Page Load even handler.
A trick to reduce the number of database queries being fired is to set a timer when the user presses a key with a timeout of say...500ms and do the databinding of gridview in timer's tick event. If you do this, database will be queried only when the user has stopped typing something.
Thanks,
Vamyip
To bind gridview data write the following code
private void GridData()
{
string conString = ConfigurationManager.ConnectionStrings["MyCon"].ToString();
SqlConnection sqlcon = new SqlConnection(conString);
SqlCommand sqlcmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
String query;
if (txtsearch.Text == "")
{
query = "select PersonID,LastName,FirstName from Person";
}
else
{
query = "select PersonID,LastName,FirstName from Person where PersonID like '" + txtsearch.Text + "%' or LastName like '" + txtsearch.Text + "%' or FirstName like '" + txtsearch.Text + "%'";
}
sqlcmd = new SqlCommand(query, sqlcon);
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
grdsearch.DataSource = dt;
grdsearch.DataBind();
}
else
{
grdsearch.DataBind();
Label1.Text = "No Records Found";
}
sqlcon.Close();
}
In page load event
if (!IsPostBack)
{
GridData();
}
for search button click event call GridData() method and
for clear button click event write following code
txtsearch.Text = "";
GridData();
Label1.Text = "";
Unless you have a specific need to do this on the server, why not perform the filtering on the client? A solution like DataTables is fast and user-friendly.
If you do other way to working search filtering condition for grid view header part. it is easy to use implement in your code. This is concepts used without database but i was using data table in linq. i hope to this code use full.
DataTable dt = (DataTable)Session["ProductTable"];
var query = from t in dt.AsEnumerable()
where t.Field<string>("ProducId").StartsWith(txtProductId.Text.ToString().Trim())
|| t.Field<string>("ProducId").Contains(txtProductId.Text.ToString().Trim())
select t;
Here is a sample program.
implement the onclick of search button like this:
protected void searchButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(searchTextBox.Text))
{
SqlDataSource1.SelectCommand = "SELECT id,name,address, datetime FROM nirmaan.[seller] where id <>0" +
" ORDER BY [name], [id]";
}
else
{
SqlDataSource1.SelectCommand = "SELECT id,name,address, datetime FROM nirmaan.[seller] where id <>0" +
"and "+DropDownList1.SelectedValue+" LIKE '%" + searchTextBox.Text + "%' ORDER BY [name], [id]";
}
GridView1.DataBind();
}

Need help in save image in sql database using asp.net

I trying to save employee image in employee database. I have three field in database table empid, empname, empimage. Here is my database part.
CREATE DATABASE [Employee]
GO
USE [Employee]
GO
CREATE TABLE EmpDetails
(
empid int IDENTITY NOT NULL,
empname varchar(20),
empimg image
)
In the button click event, i have written the following code:
SqlConnection connection = null;
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
// Insert the employee name and image into db
string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
connection = new SqlConnection(conn);
connection.Open();
string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(#enm, #eimg)SELECT ##IDENTITY";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("#enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("#eimg", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Employee ID is {0}", id);
}
catch
{
lblResult.Text = "There was an error";
}
finally
{
connection.Close();
}
And Here is my form:
<asp:Label ID="lblEmpName" runat="server" Text="Employee Name"></asp:Label>
<asp:TextBox ID="txtEName" runat="server"></asp:TextBox>
<br />
<asp:Label ID="lblImage" runat="server" Text="Employee Image"></asp:Label>
<asp:FileUpload ID="imgUpload" runat="server" />
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
&nbsp
<asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
<br />
<hr />
<asp:Image ID="Image1" style="width:200px" Runat="server" />
But when I am uploading any image and clicking on submit button getting this error "Object reference not set to an instance of an object." Pls somebody point out my error.
Thanks,
Sumit
Object Reference errors only occur when an object is not initialized and you try to reference it. This could be any object you are referencing within your code. If you step through the code while debugging, you can see exactly which reference is null.
You have an if statement that initializes the imgByte object:
imgByte = new Byte[File.ContentLength];
If the img object turns out to be null, that code does not run. Then you reference the imgByte here, regardless of whether or not the img was null:
cmd.Parameters.AddWithValue("#eimg", imgByte);
Check the the HttpPostedFile object itself is not null and move your imgByte object initialization outside the if statement. Also, the name File is already used by the System.IO.File object. You may want to rename it just to be safe.
I would rearrange your ADO.NET code a bit - make it safe and more reliable; also, I would make sure to separate the two SQL statements in your "sql" string by a semicolon to make it clear to SQL that this is two commands, really:
string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
using(connection = new SqlConnection(conn))
{
string sqlStmt = "INSERT INTO dbo.EmpDetails(empname, empimg) " +
"VALUES(#enm, #eimg); SELECT ##IDENTITY";
using(SqlCommand cmd = new SqlCommand(sqlStmt, connection))
{
cmd.Parameters.AddWithValue("#enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("#eimg", imgByte);
connection.Open();
int id = Convert.ToInt32(cmd.ExecuteScalar());
connection.Close();
lblResult.Text = String.Format("Employee ID is {0}", id);
}
}
Any luck with this?? Otherwise you should really step through the code in the debugger and see where in your code you reference something that is NULL (and you don't check for that condition).
Marc
While i am debugging this code i am
getting exception in this
line..."string conn =
ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;"
Exception is: Object reference not set
to an instance of an object.
You need to add a connection string named EmployeeConnString to web.config.
Your exception handler does not distinguish where exactly an exception occurred, and issues a single error message for any possible error.

ASP.NET adding controls inside a loop

Pardon me, this really is a noob question but please understand that I do not have much ASP.NET experience. All I need to do is:
1) Open up the following SQL query:
SELECT myid FROM mytable
2) For each record, generate this fragment of HTML:
<img src="http://someurl/__myid comes here as well__/small.png" />
Its easy for me to use the classical ASP <% do until recordset.eof ... loop %> style loops but I need it in ASP.NET style, probably perform the operation in Page_Load event and use intrinsic ASP.NET controls.
Use a repeater control. In the ItemTemplate, you can put whatever you would like to be generated for each record returned from your query.
http://articles.sitepoint.com/article/asp-net-repeater-control
add this in the aspx page source
<td id="urLink" runat="server">
</td>
add this in the Page_Load event
SqlConnection con = new SqlConnection();
con.connectionstring = "your connection database";
SqlDataReader reader;
SqlCommand command = new SqlCommand(con);
command.Commandtext = "SELECT myid FROM mytable";
command.CommandType = CommandType.Text;
reader = command.ExecuteReader();
while(reader.Read())
{
urLink.innerHTML += "<a href="#mynameanchor" onClick="myfunction( " + reader["myid"].tostring() + " );">
<img src="http://someurl/" + reader["myid"].tostring() + "/small.png" /></a>";
}
Looks like the onclick is a javascript event which means you can write out the HTML markup to a string and then append it all into a literal control. Remember to use a stringbuilder :)
here's a very basic example:
// get data from database and into a reader before
StringBuilder links = New StringBuilder();
while(reader.read())
{
links.appendFormat("<a HREF='id_{0}'>{0}</a>", reader["ID"]);
}
ltlLinks.Text = links.ToString();

Resources