I am new to asp.net and trying to do simple things first. Now i am trying to make a simple library database. In my scenario user enters the title that he needs to search and then clicks search button. Here is the screenshot of my simple user interface:
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Pages_Search : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void bSearchButton_Click(object sender, EventArgs e)
{
string searchedItem = tSearchBox.Text;
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Users\\SUUSER\\Documents\\Visual Studio 2010\\Projects\\Library\\LibWebSite\\App_Data\\LibDatabase.mdf;Integrated Security=True;User Instance=True";
Int32 verify;
string query1 = "";
if (SearchBy.SelectedValue == "Search by title")
{
query1 = "Select count(*) from Items where Title='" + tSearchBox.Text + "'";
}
}
}
My question is, my query finds the number of items with that title, but does not print each item to the screen. How can i print out the search results to the screen? I mean how can i show the search results in another web page? I appreciate any helps.
Thanks
Tutorials such as this should help:
http://www.codeproject.com/Articles/8659/Mastering-ASP-NET-DataBinding
Change your query to:
"Select Title,count(1) from Items where Title='" + tSearchBox.Text + "'";
Related
This is my first question here at Stack Overflow and i will be as precise as possible.
I am working on an ASP.NET Web application and i have a gridview which have a XML as a datasource. I already have it bound as a datasource and it works perfect.
I have a textbox and a button in my project and want to search in the gridview.
Here is an example of one of the nodes in the XML file.
https://i.imgur.com/weTlrh1.png
The problem I currently have is that I am stuck at the search gridview part.
I have as I said before a textbox and a button and when i write a value in the textbox and press on the button i want to search the gridview and its nodes to check if for an example any titles contains the words from the textbox.
Right now I have the corresponding code:
https://i.imgur.com/l2lz8JL.png
This code is in the buttonSearch Click event. The SearchBookBox.text is the Text i want to search for in the Gridview.
I am stuck right now and i need some help.
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("/NewFolder1/books.xml"));
GridView1.DataSource = ds;
GridView1.DataBind();
The above code is the code which i bind the gridview to the corresponding xml file. This code is in my Page_Load Event.
I have tried different ideas to solve this issue, but nothing works.
Right now the code is like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace BookSearch
{
public partial class BookSearchForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ErrorLabel.Visible = false;
AddBooksXML();
}
private void AddBooksXML()
{
if (!IsPostBack)
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("/NewFolder1/books.xml"));
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
protected void BookSearchButton_Click(object sender, EventArgs e)
{
if(SearchBookBox.Text != null)
{
foreach (XmlNode node in ds.GetXml)
{
}
}
else
{
Response.Write("ERROR!");
}
}
}
}
I really need some help. As i said, i have tried different ideas, but I am stuck and I can't get anywhere.
I think this is a possible solution.
protected void XmlSearch(string searchText)
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("/NewFolder1/books.xml"));
var dat = from books in ds.Tables[0].AsEnumerable()
where books.Field<string>("author") == searchText || book.Field<string>("title") == searchText
select books;
GridView1.DataSource = dat.CopyToDataTable();
GridView1.DataBind();
}
This will search in author and title for exact matches its probably not the best solution but its a example of how you could do it.
Requires
using System.Linq;
EDIT
If you wanna loop through them you can use
foreach (var book in dat)
{
var bookInfo = String.Format("{0} {1}", book["author"].ToString(), book["title"].ToString());
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
binddata();
}
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
void binddata()
{
string pid = Request.QueryString["Prod_Id"];
con = new SqlConnection("Data Source=.\\sqlexpress; initial catalog=PracticeDb; user id=sa; pwd=manager;");
con.Open();
da = new SqlDataAdapter("Select * from Products where Prod_Id='" + pid + "'", con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
listview.DataSource = ds;
listview.DataBind();
}
}
}
the user is directed to the record updation page when he click the edit link in the record list page. what should i do write in datasource and databind
You have to extract the values from DataSet like
string name = ds.Tables[0].Rows[0]["name"].ToString();
Here i am assuming that you have a name as a field in your select query, you have to use your fields.
After getting that field assign it to TextBox like
TextBox1.Text = name ;
After that run your update query based on Primary Key.
One Important Suggestion :-
Try to use Page.IsPostBack property of your Page on Page_Load.Need to change your Page_Load like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
binddata();
}
}
Hope you understand and works for you.
Try to use this.
TextBox1.Text = ds.Tables[0].Rows[0]["name"].Tostring();
I checked above notes but they are not helpful.I am using VS2008 for ASP.Net and MS Access 2010 as a database.
I need to upload the data from excel to database through ASP web page.
But I am receiving an error as below :
"The Microsoft Jet database engine cannot open the file 'C:\Users\poonamj\Documents\Visual Studio 2008\Projects\SmartTool\SmartTool\Uploads\'. It is already opened exclusively by another user, or you need permission to view its data."
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Collections.Generic;
using System.Data.OleDb;
namespace SmartTool
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void UploadFile(object sender, EventArgs e)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
Response.Redirect(Request.Url.AbsoluteUri);
}
protected void DownloadFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
Response.WriteFile(filePath);
Response.End();
}
protected void DeleteFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
File.Delete(filePath);
Response.Redirect(Request.Url.AbsoluteUri);
}
protected void ViewFile(object sender, EventArgs e)
{
//string filePath = (sender as LinkButton).CommandArgument;
// File.ReadAllLines(filePath);
//GridView2.DataSource = File.ReadAllLines(filePath);
//GridView2.DataBind();
//string[] content = File.ReadAllLines(filePath);
//GridView2.DataSource = content.
// OleDbConnection conn = new OleDbConnection();
// conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/Users/poonamj/Documents/Visual Studio 2008/Projects/SmartTool/SmartTool/fallout.accdb;User id=admin;Password=";
// conn.Open();
string Access = Server.MapPath("App_Data/fallout.accdb");
string Excel = Server.MapPath("~/Uploads/");
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Excel + ";Extended Properties=Excel 8.0;Mode=12;";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT * INTO [MS Access;Database=" + Access + "].[New Table] FROM [Sheet1$]";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Uploads/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
files.Add(new ListItem(Path.GetFileName(filePath), filePath));
}
GridView1.DataSource = files;
GridView1.DataBind();
}
}
}
}
I wanted to comment, but cannot.
Did you check the following? Each one enlists possible solutions that can help you.
Official Microsoft Support page: http://support.microsoft.com/kb/306269
http://social.msdn.microsoft.com/forums/en-US/adodotnetdataproviders/thread/3479cc5a-2bca-4e9c-9fdb-ec3f96065a52
Additionally, try using the full path including the file name for your Data Source. The following is flawed:
string Excel = Server.MapPath("~/Uploads/");
You want to append the Excel file name after Uploads/.
I've used a tool like this to troubleshoot the problem in the past: http://www.filehippo.com/download_unlocker/ , more importantly it's view locks on a directory functionality.
I dunno, if I'm overthinking this, but 'C:\Users\poonamj\Documents\Visual Studio 2008\Projects\SmartTool\SmartTool\Uploads\' is a directory, where it seems to be expecting a file.
An example would be 'C:\Users\poonamj\Documents\Visual Studio 2008\Projects\SmartTool\SmartTool\Uploads\db.mdb' is a path to a file.
You aren't specifying a file name for Excel and that is causing the exception.
string Excel = Server.MapPath("~/Uploads/MyFile.xls");
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Excel + ";Extended Properties=Excel 8.0;Mode=12;";
Add a file name to Excel and this problem should be solved.
I have a createuserwizard (cuw) control and I want to add more fields (customizing). I need to store this info in a database called 'UserProfiles'. I´ve added a fileupload control to store an image (avatar) and the problem is here. When I refresh my database (after I filled the cuw control) I can see the new data for all the columns, EXCEPT for the image column. I supose the problem is in the code behind. This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
CreateUserProfile(CreateUserWizard1.UserName, txtFirstName.Text, txtLastName.Text, CreateUserWizard1.Email, CreateUserWizard1.Password, imgUpload.FileName);
}
private void CreateUserProfile(string UserName, string Gender, string LookingFor, string Email, string Password, string Image)
{
string conString = WebConfigurationManager.ConnectionStrings["UserProfiles"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand("INSERT UserProfiles (UserName,Gender,LookingFor,EMail,Password,Image) VALUES (#UserName,#Gender,#LookingFor,#EMail,#Password,#Image)", con);
cmd.Parameters.AddWithValue("#UserName", UserName);
cmd.Parameters.AddWithValue("#Gender", Gender);
cmd.Parameters.AddWithValue("#LookingFor", LookingFor);
cmd.Parameters.AddWithValue("#EMail", Email);
cmd.Parameters.AddWithValue("#Password", Password);
cmd.Parameters.AddWithValue("#Image", Image);
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
}
I´m a beginner. Thanks in advance for your help.
Im designing my web page, in that i have typed in the book id and typed Nameofthebook. and then click the button the stack of book are available is go to another page and then not available is display the error message is book is not available My project (Library management system)
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class Bookcheck : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string constr = null;
constr = ConfigurationManager.ConnectionStrings["librarymanagementconnetionstring"].ConnectionString;
SqlConnection cnn = new SqlConnection(constr);
cnn.Open();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("SELECT*FROM BOOKREGISTRATIONDETAILS WHERE bookId='" + txtid.Text.Trim() + "'AND Nameofbook='" + txtnb.Text.Trim() + "'", constr);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
Response.Redirect("Issueofbook.aspx");
}
else
{
Msg.Text = "NO book available";
Msg.Visible = true;
}
}
}
Error:
Object reference not set to an instance of an object.
I noticed that in librarymanagementconnetionstring, connection is spelled incorrectly. Is this the correct entry in your web.config for the connection string?
I'd say that it's the line
if (ds.Tables[0].Rows.Count > 0)
that giving the error.
If your DataSet has no tables then ds.Tables could be null.
If that's a possibility then you need to code for that.
If there are no rows ds.Tables[0].Rows won't be null and your test should work.
Change
if (ds.Tables[0].Rows.Count > 0)
to
if(ds.HasRows)