Passing QueryString into another Entity Framework page - c#

I have a web form (Page1.aspx) in which I am passing an ID as query string to another page (Page2.aspx).
Now in this page I have EntityDataSource which binds to GridView. How should I populate this gridview with that ID?
Eg. If my ID is 1056, then in my DataGridView in Page2.aspx should populate elements of this ID.
This is the code:
protected void Page_Load(object sender, EventArgs e)
{
string getEntity = Request.QueryString["EntityID"];
int getIntEntity = Int32.Parse(getEntity);
if (getIntEntity != 0)
{
//What should I do here???
}
}
What should I do? Thank You!

See "Using a Control Parameter to Set the "Where" Property" in this tutorial:
http://www.asp.net/entity-framework/tutorials/the-entity-framework-and-aspnet-–-getting-started-part-3
The process will be similar except as "Parameter source" select QueryString instead of Control.

1.Take id from query string:
var strId = HttpContext.Current.Request.QueryString["ID"];
int id = 0;
int.TryParse(strId, out id);
if(id != 0)
{
...
}
2.Pass id to DataSource(mb this article help you) in Page_load event.

Related

Set the value of an unbound DropDownList based on values passed in a querystring

I'm trying to set the value of an unbound DropDownList based on values passed in a query string without success.
I don't have error but in DropDownList the value passed in a query string is not selected.
Here is my code.
In page1.aspx:
Server.Transfer("page2.aspx?dt=" + myDateDDL.SelectedItem.ToString());
In page2.aspx:
Server.Transfer("page1.aspx?dt=" + Request.QueryString["dt"].ToString());
In page1.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (!String.IsNullOrWhiteSpace(Request.QueryString["dt"]))
{
myDateDDL.SelectedValue = Request.QueryString["dt"].ToString();
}
}
}
Please help me.
Thank you in advance.
You can't pass value in query string using Server.Transfer.
Use Response.Redirect() to pass query string it will solve your issue.
Example
Response.Redirect("page2.aspx?dt=" + myDateDDL.SelectedValue.ToString());
Differences between Server.Transfer and Response.Redirect

How to save option selected in Dropdownlist after selection

I am displaying columns in a GridView and one of the columns is a dropdownlist. I want to be able to save the option selected in the dropdownlist as soon as something is selected. I have done this with one of the columns that has a textbox so I was hoping to do something similar with the DropDownList.
The code for the textbox and dropdownlist:
protected void gvPieceDetails_ItemDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
JobPieceSerialNo SerNo = e.Row.DataItem as JobPieceSerialNo;
if (SerNo != null) {
TextBox txtComment = e.Row.FindControl("txtComment") as TextBox;
txtComment.Text = SerNo.Comment;
txtComment.Attributes.Add("onblur", "UpdateSerialComment(" + SerNo.ID.ToString() + ", this.value);");
DropDownList ddlReasons = (e.Row.FindControl("ddlReasons") as DropDownList);
DataSet dsReasons = DataUtils.GetUnapprovedReasons(Company.Current.CompanyID, "", true, "DBRIEF");
ddlReasons.DataSource = dsReasons;
ddlReasons.DataTextField = "Description";
ddlReasons.DataValueField = "Description";
ddlReasons.DataBind();
ddlReasons.Items.Insert(0, new ListItem("Reason"));
}
}
How to I create an update function for a dropdownlist?
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
string sel = ddlReasons.SelectedValue.ToString();
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; //can't find sel value
SerNo.Update();
}
Dropdownlist:
<asp:DropDownList ID="ddlReasons" runat="server" OnSelectedIndexChanged="DDLReasons_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
I created an OnSelectedIndexChanged function to get the selected value. But how do I then save that value? Is there a way to pass it into the UpdateSerialReason function?
Just move the string sel declaration outside the scope of DDLReasons_SelectedIndexChanged and get the Text of the SelectedItem since it's included in your data source.
private string sel;
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
sel = ddlReasons.SelectedItem.Text;
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; // Should now be available
SerNo.Update();
}
The way you had it previously it was only available in the local scope, i.e, inside the method in which it was being declared and used.
You can get selected value when you call your function:
UpdateSerialReason(/*Some SerNoID*/ 123456, ddlReasons.SelectedValue)
You will lose your value after postback is done if you save value to variable as Equalsk suggested. If you need to use your value on the other page you can save it in session.
If you are working within one asp.net page you can do as I suggested above. Then you can skip the postback on your DropDownList and call UpdateSerialReason when you need :)
And you might want to add property ViewStateMode="Enabled" and EnableViewState="true"

Retrieve data from database and show in detailsview

I want to retrieve data from database on the current logged in SharePoint user and show it on a control in a detailsview. But I really don't know how to achieve that on the best way. This is a code I've tried but it shows null.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
GetEmployeeCv();
}
}
private void GetEmployeeCv()
{
using (var db = new KnowItCvdbEntities())
{
SPWeb theSite = SPControl.GetContextWeb(Context);
SPUser theUser = theSite.CurrentUser;
string strUserName = theUser.LoginName;
var theEmpl =(from p in db.EMPLOYEES
where p.username == strUserName
select p).FirstOrDefault();
if(theEmpl != null)
{
Image empImg = (Image)DetailsViewShowFullCv.FindControl("imageProfPic");
empImg.ImageUrl = theEmpl.image;
}
}
}
If I want to databind my detailsview like:
Image empImg = (Image)DetailsViewShowFullCv.FindControl("imageProfPic");
empImg.ImageUrl = theEmpl.image;
DetailsViewShowFullCv.DataSource = ??;
DetailsViewShowFullCv.DataBind();
I don't really know how to do it. Anyone out there that can help me out?
a) The DataSource should be the variable which holds the data. In this case it would be theEmpl
b) Run this through the debugger to check if strUserName is what you expect. The LoginName field typically returns the domain and username like "DOMAIN\UserName" so there's a chance that it will return a null (null by default) value if you're only storing the UserName part in the database without the Domain\
c) For Databinding, either change your LINQ query to p.FieldNameToDatabind or know how to write the Databind code in asp markup so that you can actually display the field.

Modal popup extender losing ID

Edit:
Added onload method:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["usersName"] != null)
{
object a = Session["_id"];
IDMaster = Convert.ToInt32(a);
GridView1.Columns[10].Visible = true;
GridView1.Columns[11].Visible = true;
}
I'm using a modal pop up extender to warn my customers that the item amount of a specific item is over a certain amount.
I have two buttons within this extender that allows a user to confirm they want an email sending to them when new stock arrives or not.
The trigger for the 'yes' button works perfectly but when i send the row ID to the constructor of my class used to store the email details it is always set to 0, even though the variable is global.
Here is my code to explain the issue further:
Button within my modal to add items to the cart:
protected void LinkButton1_Click(object sender, EventArgs e)
{
GridViewRow row = ((Button)sender).Parent.Parent as GridViewRow;
TextBox t = (TextBox)row.FindControl("txtQuan");
*********Gain the item row ID (this is what needs to be passed*******
object ID = GridView1.DataKeys[row.RowIndex].Value;
*********This ID should be passed but is setting to 0************
rowID = Convert.ToInt32(ID);
string qty = t.Text;
int stockToAdd = Convert.ToInt32(qty);
DBHandler add = new DBHandler(rowID);
int qtyCheck = add.getStockQty();
if (stockToAdd > qtyCheck)
{
Button2_ModalPopupExtender.Show();
}
else{
SqlConnection con;
con = add.openDB();
con.Open();
DBHandler idCheck = new DBHandler(rowID);
int rows = idCheck.checkCartRows();
if (rows > 0)
{
int qtyNow = idCheck.getCartQty();
int updateStock = qtyNow + stockToAdd;
idCheck.updateQty(rowID, updateStock);
updatePanel();
}
else
{
idCheck.insertCart(qty);
updatePanel();
}
add.close();
}
}
The following code shows my confirm onclick button method. Note the ID 'rowID' that was stored in the above method when the add to cart button was clicked. This rowID is is setting to 0 instead of holding the rowID value.
protected void btnOK_Click(object sender, EventArgs e)
{
***** rowID is setting to 0*******
DBoutOfStockEmail insertNewEmailDetail = new DBoutOfStockEmail(IDMaster, rowID);
DBMembershipHandler getEmail = new DBMembershipHandler(IDMaster);
string emailToSend = getEmail.emailOfMember();
insertNewEmailDetail.insertDetails(emailToSend);
}
To summaries this question: Why is the rowID variable setting to '0' when i click the yes button with the modal pop up extender?
Based on my initial Comment I am going to post this as an answer
This can be from several things.. are you checking or doing IsPostBack checks, are you holding the Value(s) in a Session Variable..? ViewState is it enabled or disabled..? can you show what your Page_Load Event Looks like

How can I use the selected rows in GridView as a source for a GridView in another page?

I am writing a web site in Visual Studio, something like an on-line library. I have a GridView on the first page that presents all of the books available from the data source and some other properties also contained in the data source. The GridView contains check boxes and the user can choose which books he wants to order by checking a box. My question is how can I use the data in the selected rows, the list of books with their properties and show that list on another page, so that the user is able to know which items he has selected?
I tried with a for loop on the FirstPage:
protected void Page_Load(object sender, EventArgs e)
{
List<int> ids = new List<int>();
if (!IsPostBack)
{
}
else
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
int bookID = (int)GridView1.DataKeys[i][0];
CheckBox cb = (CheckBox)GridView1.Rows[i].FindControl("CheckBox");
if (cb.Checked)
{
ids.Add(bookID);
}
}
Session["Ids"] = ids;
Response.Redirect("SecondPage.aspx");
}
}
and on the SecondPage:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtBooks = new DataTable("Books");
dtBooks.Columns.Add(new DataColumn("ID", typeof(int)));
if (!IsPostBack)
{
var list = (List<int>)Session["Ids"];
foreach (int id in list)
{
if (Request.QueryString["bookID" + id] != null)
{
DataRow row;
row = dtBooks.NewRow();
row["ID"] = Request.QueryString["bookID" + id];
dtBooks.Rows.Add(row);
}
}
GridView1.DataSource = dtBooks;
GridView1.DataBind();
}
else
{
}
}
but I get no GridView table on the second page. I would be very grateful if anyone notices my mistake and points it out. Hope you can help me.
This is a common issue when setting session variables before a redirect. I think you can work around it by using the overloaded Response.Redirect method:
Response.Redirect("...", false); // false = don't stop execution
See here for more details:
Session variables lost after Response.Redirect
Another option is to store the IDs in a hidden field, and access them with Page.PreviousPage, like this:
HiddenField hidden = (HiddenField)Page.PreviousPage.FindControl("MyHiddenField");
string values = hidden.Value;
Lastly, depending on what the page is doing, you might want to use Server.Transfer here. There are drawbacks to this approach, but there are situations where it's applicable.
In your second page, you are checking for a query string variable before adding a row to dtBooks:
if (Request.QueryString["bookID" + id] != null)
However, you are not passing any query strings when you redirect:
Response.Redirect("SecondPage.aspx");
At a guess, I would think that you originally tried using the query string to pass the IDs, before changing to the session and you haven't updated all of your code.
I am somewhat concerned about your first page code, though. You do realize that you will redirect to the second page whenever a post back occurs? That means that no matter what buttons / controls you have on the first page, if they post back for any reason, you will redirect to the second page.
EDIT AFTER COMMENTS
If you aren't using the query string, then don't use the query string:
foreach (int id in list)
{
DataRow row;
row = dtBooks.NewRow();
row["ID"] = id;
dtBooks.Rows.Add(row);
}

Categories

Resources