I have a table tblProfile, which contains fields with Id, Name, Address. I have 2 aspx page, which are Home.aspx and Here.aspx. On my Home.aspx I have used this code to pass the Id in my Here.aspx:
<asp:HyperLink ID="link" runat="server" NavigateUrl="Here.aspx?id={0}"
Font-Names="Times New Roman" Font-Size="Medium" >Click here</asp:HyperLink>
In code behind Home.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
string bID = Request.QueryString["Id"];
if (string.IsNullOrEmpty(Id))
{
Response.Redirect("Here.aspx?", true);
}
ViewState["Id"] = Id;
link.NavigateUrl = String.Format(link.NavigateUrl, Id);
}
I don't have any problem with passing the Id to url in 2nd page. But what I want right now is, on my Here.aspx, I have 3 textboxes which supposed to be filled by the Id, Name and Address of the certain Id that passed from the Home.aspx. Tried many but had no luck at all. Any help would be appreciated. By the way, I'm using asp.net with c#.
We are having two solution for it
Solution 1 : User Previous page property in asp.net so that you no need to pass ID. i.e.
protected void Page_Load(object sender, EventArgs e)
{
// Find the name on the previous page
TextBox txt = (TextBox)Page.PreviousPage.FindControl("txtNameText");
if (txt != null)
txtName.Text = Server.HtmlEncode(txt.Text);
else
txtName.Text = "[Name Not available]";
}
Solution 2 : Get ID from query string and get Data by ID in assign on text box text property.i.e.
protected void Page_Load(object sender, EventArgs e)
{
// Get value from query string
string profileID = Request.QueryString["Id"];
// Fetch data from database by ID
DataTable dt = FetchEmployeeDataByID(ProfileID);
txtName.text = dt.rows[0]["Name"].tostring();
}
From your reply on comments, I suggest to do the following:
Load your data in Here.aspx back-end (.cs file) by the Id that you retrieve from query string
Show the loaded data into your desired textbox.
You can get the name and address by retrieving the profile data from the database using the Id from the query string as the key.
So in your Here.aspx's code behind:
protected void Page_Load(object sender, EventArgs e)
{
string profileID = Request.QueryString["Id"];
// Retrive profile in your db..
var profile = Profiles.Get(p => p.ProfileID == profileID);
// Populate the textboxes
txtId.Text = profileID;
txtName.Text = profile.Name;
txtAddress.Text = profile.Address;
}
Related
I get this error:
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name:index.
Same code was running perfectly in windows form app, but in asp.net i see this error.
My code is here:
public partial class Timeline : System.Web.UI.Page
{
TwitterService servis;
ListBox tweetid = new ListBox();
protected void Page_Load(object sender, EventArgs e)
{
servis = new TwitterService(consumer key,secret,token,token);
tweetid.Items.Clear();
ListBox2.Items.Clear();
IEnumerable<TwitterStatus> anasayfa = servis.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions { Count = 200 });
var gelen = servis.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions { Count = 200, MaxId = anasayfa.Last().Id });
foreach (var tweet in gelen)
{
tweetid.Items.Add(tweet.Id.ToString());
ListBox2.Items.Add(tweet.Text);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
servis.Retweet(new RetweetOptions() { Id = long.Parse(tweetid.Items[ListBox2.SelectedIndex].ToString())});
String uyarı = "alert('Retweetlendi!');";
ClientScript.RegisterOnSubmitStatement(this.GetType(), "ConfirmSubmit", uyarı);
}
}
The problem here is that you have two ListBoxes, one (tweetid) storing the id's (presumably a key of sorts) of the tweets, and the other (ListBox2) storing the text of the tweets. You also don't seem to be adding the dynamically created tweetid ListBox to the page anywhere (and presumably the intention is that the tweetid ListBox is hidden or similar).
You are then attempting to store synchronize the selected text drop down back to the original tweetid in the code behind Button click handler, based on the relative indexes of the data - it is apparant that the two listboxes are getting out of synch, plus, you aren't validating the user has selected a valid item, hence the ArgumentOutOfRange exception.
Although in theory this could be made to work, e.g. by ensuring that the data isn't lost in each page_load roundtrip as per #Dan's answer, and also by enabling ViewState, this all seems rather fragile to me.
I would propose that instead, you use a single ListBox and use the DataTextField to show the tweet to the user, and the DataValueField to track the Id of each tweet:
.aspx
<asp:ListBox runat="server" ID="TweetsListBox" DataTextField="Text" DataValueField="Id" EnableViewState="True" />
.aspx.cs Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Replace with your code to fetch tweets here
TweetsListBox.DataSource = FetchSomeTweets();
// We've alread set the names of the properties to use `Id` and `Text` in the aspx
TweetsListBox.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
long tweetIdToRetweet;
if (long.TryParse(TweetsListBox.SelectedValue, out tweetIdToRetweet))
{
servis.Retweet(new RetweetOptions() { Id = tweetIdToRetweet });
}
else
{
// Display Error that user must select a tweet
}
}
For test purposes, I used the following mock models for your tweet service:
class Tweet
{
public int Id { get; set; }
public string Text { get; set; }
}
private static readonly IEnumerable<Tweet> SomeTweets = new[]
{
new Tweet { Id = 123, Text = "This is tweet 123" },
new Tweet { Id = 234, Text = "This is tweet 234" },
new Tweet { Id = 345, Text = "This is tweet 345" }
};
Your Page_Load method is populating the ListBox everytime the page postback, even before your button click event.
Thus, ListBox2.SelectedIndex will not be the the index that the user selected, since it is freshly populated in the Page_Load method.
You should add a postback check on your page_load and only populate the ListBox if the request is not a postback.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
servis = new TwitterService(consumer key,secret,token,token);
tweetid.Items.Clear();
ListBox2.Items.Clear();
IEnumerable<TwitterStatus> anasayfa = servis.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions { Count = 200 });
var gelen = servis.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions { Count = 200, MaxId = anasayfa.Last().Id });
foreach (var tweet in gelen)
{
tweetid.Items.Add(tweet.Id.ToString());
ListBox2.Items.Add(tweet.Text);
}
}
}
I am retrieving data from table column where I have saved tags for the article, for example: "animals dogs cats" and showing this string text in linkbutton. If I click it, then page is redirected to "Tags.aspx?name=animals dogs cats".
Is it possible to redirect page to "Tags.aspx?name=cats"
if I have clicked on "cats", or maybe to split the string and show each word in own linkbutton (without using something like listview)?
Thanks, Oak
If you don't want to use a web-databound control like Repeater you can create the LinkButtons dynamically. Remember to recreate them on postbacks with the same ID as before in Page_Load at the latest:
protected void Page_Init(object sender, EventArgs e)
{
createTagButtons();
}
private void createTagButtons()
{
var tblTags = new DataTable();
using (var con = new SqlConnection(connectionString))
using (var da = new SqlDataAdapter("SELECT TagID, TagName FROM dbo.Tags ORDER BY TagName", con))
{
da.Fill(tblTags);
}
foreach (DataRow row in tblTags.Rows)
{
int tagID = row.Field<int>("TagID");
string tagName = row.Field<string>("TagName");
LinkButton tagButton = new LinkButton();
tagButton.ID = "tagButton_" + tagID;
tagButton.CommandArgument = tagName;
tagButton.Click += TagLinkClicked;
this.TagPanel.Controls.Add(tagButton);
}
}
private void TagLinkClicked(Object sender, EventArgs e)
{
LinkButton tagLink = (LinkButton)sender;
string url = string.Format("Tags.aspx?name={0}", tagLink.CommandArgument);
Response.Redirect(url);
}
On the aspx you could use a Panel:
<asp:Panel ID="TagPanel" runat="server"></asp:Panel>
You can use string[] words = your_string.Split(); and then create buttons using loop
A link will show only one view called from the controller.
That is, if you have a tag "cat" and this tag is related with some view then this tag calls that view which is written in the controller.
I am currently working on my first website. The problem I have encountered is the following: I have created a paged titled "CustomerList" that obviously list customers from an sql server DB. I have made the records clickable without using the select button that is included in the GridView. When I click a record, it takes me to my desired page. However, I can't seem to find a way to write an sql query from that click event to my desired page. The following is my code for the click event:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
if (row.RowIndex == 0)
{
Response.Redirect("UsageHistoryPage.aspx? EntityID="
+ row.Cells[0].Text);
}
}
As you can see, when I click an index, I go to the "UsageHistoryPage". I've also added row.cells.[0] to take that data and write it to the UsageHistoryPage, which in my case, would be the customers name at the top of the page. Can someone please help me with this? Does anyone have a good tutorial link? thanks.
You can try with this code - Add this code on your UsageHistoryPage
var input = Response.QueryString["EntityId"];
var connectionString = "...";
var queryString = "SELECT Name FROM TABLE WHERE COLUMN=#EntityId";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
using(var command = new SqlCommand(queryString, connection))
{
Command.Parameters.AddWithValue("#EntityId",input)
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
Response.Write(String.Format("For Rick Your Name is here{0}", reader[0]));
}
}
}
#Rick you may want to look at how to check if a row is selected for example you don't need the for loop but in my case example need to check if RowIndex is = 1 or > 0 not ==0
private void myButton_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in usersGrid.Rows)
{
if (this.usersGrid.SelectedRows.Count == 1)
{
// get information of 1st column from the row
string selectedUser = this.usersGrid.SelectedRows[0].Cells[0].ToString();
}
}
}
What you need to do is something like this to make sure that a Row has been selected
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
DataGridViewRow row = GridView1.SelectedRow;
if (this.row.SelectedRows.Count == 1)
{
Response.Redirect("UsageHistoryPage.aspx?EntityID=" + row.SelectedRows[0].Cells[0].ToString());
}
}
If you want to have the Customer's name show up, on the Page Load of the UsageHistorPage.aspx add this code
String strCustName = Request.QueryString["EntityID1"];
this.Page.Title = strCustName;
try something like that.. please let someone here know if any of the ideas are working for you.
I am creating a website. The home page has a text box and drop down box in which the user enters the movie name and language to search. When the user clicks on the Search button the search result page is displayed and the results of search should be displayed in a data grid. I created session variables to pass the text of the text box and data grid to be used in the other page. The code to fetch data from the database is in a class how do i pass the values received from the database to a method of another page? This is the code i have written, it doesn't give any errors but the data grid does not get filled with results what am I doing wrong?
//Code for search button in home page
protected void Btnsearch_Click(object sender, EventArgs e)
{
Response.Redirect("SearchResults.aspx");
Session["moviename"] = TextBox3.Text;
Session["language"] = DropDownList1.Text;
}
//Code to fetch data from database
public class movie
{
public SqlDataAdapter searchmovie(object moviename, object language)
{
connection.con.Open();
SqlDataAdapter adapter1 = new SqlDataAdapter("select
select movieName,language,director,price from movie
where moviename = '" + moviename + "' and
language = '" + language + "'",
return adapter1;
}
}
//Code in search page to fill data grid with search results
public partial class SearchResults : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
movie m = new movie();
SqlDataAdapter movieDetails = m.searchmovie(Session["moviename"],
Session["language"]);
DataSet data = new DataSet();
movieDetails.Fill(data, "movieD");
GridView1.DataSource = data.Tables["movieD"];
GridView1.DataBind();
}
}
Set the session variables before redirecting, like this:
protected void Btnsearch_Click(object sender, EventArgs e)
{
Session["moviename"] = TextBox3.Text;
Session["language"] = DropDownList1.Text;
Response.Redirect("SearchResults.aspx");
}
I would like to suggest to avoid Session as data storage.
ASP.NET has a nice feature called cross-posting: it make you able all the page control and state from a page to another.
http://msdn.microsoft.com/en-us/library/ms178139.aspx
Personally, I really love feature because you can refer to page as object, having controls exposed ad property!
I have a Gridview which displays the filenames in the database.
I have written code for deleting filename entry from database, but I also want to delete it from the directory, so how do I retrieve filename from Gridview ?
I don't want to execute another select command for retrieving filename.
Code :
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int Fid = (int)GridView1.DataKeys[e.RowIndex].Value;
sdsFiles.DeleteCommand = "Delete from Files where Fid = #id";
sdsFiles.DeleteParameters.Clear();
sdsFiles.DeleteParameters.Add("id",Fid.ToString());
sdsFiles.Delete();
System.IO.Directory.Delete(Server.MapPath("~/Data/"));
}
Thanks.
Use the following code and do steps;
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int Fid = (int)GridView1.DataKeys[e.RowIndex].Value;
sdsFiles.DeleteCommand = "Delete from Files where Fid = #id";
sdsFiles.DeleteParameters.Clear();
sdsFiles.DeleteParameters.Add("id",Fid.ToString());
sdsFiles.Delete();
string fileName = ((Label)GridView1.Rows[e.RowIndex].FindControl("Label1")).Text;
System.IO.File.Delete(Server.MapPath("") + "\\" + fileName);
}
you must go to gridview columns
window
Convert to file name column to
TemplateField
Save and Exit GridView Columns window
Go to Files column template design
Set label id "Label1"
Go to code and use it
For performance reasons I, wouldn't go overboard adding lots of keys with this, but you can set the GridView's DataKeys property to include the filename column as well as the fid that you already set by setting the GridViews DataKeyNames property equal to "FID,Filename", then retrieve the DataKey by row during your delete method using the GridView1.DataKeys[e.RowIndex].Values method instead, where retrieve the DataKey by index, so if your DataKeys are "FID,filename" FID would be GridView1.DataKeys[e.RowIndex].Values[0] and filename would be GridView1.DataKeys[e.RowIndex].Values[1].
I get the string (file name) direct this way:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView1.SelectedIndex = e.RowIndex;
string fileName = GridView1.SelectedRow.Cells[1].Text;
System.IO.File.Delete(Server.MapPath("") + "\\" + fileName);
int Fid = (int)GridView1.DataKeys[e.RowIndex].Value;
sdsFiles.DeleteCommand = "Delete from Files where Fid = #id";
sdsFiles.DeleteParameters.Clear();
sdsFiles.DeleteParameters.Add("id",Fid.ToString());
sdsFiles.Delete();
GridView1.SelectedIndex = -1;
}
Maybe there is ever faster, I am not sure.