Not able to display content in <EditItemTemplate> in FormView - c#

What am I doing wrong since the content in the < EditItemTemplate > is not displayed when I click the Edit button?
<asp:FormView runat="server" id="fwHotelDetails" DataKeyNames="id" OnDataBound="fwHotelDetails_DataBound" OnModeChanging="fwHotelDetails_ModeChanging">
<ItemTemplate>
//display content here
<asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" />
</ItemTemplate>
<EditItemTemplate>
This text should be displayed when I click the Edit button
<asp:LinkButton runat="server" ID="UpDateButton" CausesValidation="false" CommandName="Update" Text="Lagre" />
</EditItemTemplate>
</asp:FormView>
Update
This is my code-behind:
namespace development.templates
{
public partial class HotelDetails : TemplatePage
{
static Hotel hotel;
protected DataRow drHotel;
DataTable dtCriteria;
DataTable dtHotel;
private HotelCriteria hotelCriteria;
protected void Page_Load(object sender, EventArgs e)
{
int hotelID = Convert.ToInt32(Request.QueryString["hotelid"].ToString());
if (!IsPostBack)
{
if (hotelID != 0)
{
// Create Hotel instance based on hoteID.
hotel = new Hotel(hotelID);
drHotel = hotel.hotelData.Rows[0];
dtHotel = hotel.getHotelsByCity(drHotel["city"].ToString());
// Hotel scrore is calculated from a score which is derived from certain criterias.
hotelCriteria = new HotelCriteria(hotelID);
dtCriteria = hotelCriteria.getHotelCriteria();
//Set datasource for hotel list in right sidebar.
hotelListByCity.DataSource = correctList(dtHotel, hotelID);
hotelListByCity.DataBind();
// Set datasource for current hotel
fwHotelDetails.DataSource = hotel.hotelData;
fwHotelDetails.DataBind();
}
}
}
protected void fwHotelDetails_DataBound(object sender, EventArgs e)
{
//Find the criteria list and set the datasource
Repeater rep = (Repeater)fwHotelDetails.FindControl("repCriteriaScore");
rep.DataSource = this.dtCriteria;
rep.DataBind();
// Controll is user is logged in. If logged in, then user may add, edit or delete hotel record.
System.Security.Principal.IPrincipal user = Context.User;
if ((user != null) && user.Identity.IsAuthenticated){
Panel panel = (Panel)fwHotelDetails.FindControl("administrationPanel");
panel.Visible = true;
}
}
protected void fwHotelDetails_ModeChanging(object sender, FormViewModeEventArgs e)
{
switch (e.NewMode)
{
case FormViewMode.Edit:
MessageLabel.Text = "Edit mode";
fwHotelDetails.ChangeMode(FormViewMode.Edit);
break;
case FormViewMode.ReadOnly:
MessageLabel.Text = "Read mode";
break;
case FormViewMode.Insert:
MessageLabel.Text = "Insert mode";
break;
}
}
}
}

The EditItemTemplate also won't show up if the record is empty. In other words, if you have a gridview that you select a detail record from that is feeding the formview, and their is no detail for the selected grid item, then the form won't show up at all. I check to see if the detail record is null, and if so, I set the formview or detailsview to "insert" mode. so they can enter a new record.

In your function fwHotelDetails_ModeChanging, add this:
fwHotelDetails.ChangeMode(FormViewMode.Edit)
i.e.
Protected Sub fwHotelDetails_ModeChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewModeEventArgs) Handles fwHotelDetails.ModeChanging
fwHotelDetails.ChangeMode(FormViewMode.Edit)
End Sub

Ok have you tried putting a breakpoint on fwHotelDetails_ModeChanging and then debugging the App? Does the breakpoint get hit when you click the edit button.
At least this will tell you where your problem lies. That is [1] the events are not hooked up correctly or [2] there is something going wrong with ChangeMode.
I realise this isnt a solution but if you tell me whether the breakpoint hits i can help you further.

Related

Is there any way to pass LinkButton content from one to another while redirecting?

I want to pass or store in Session Item clicked in GridView from one Page to another and passing the same parameter to my Stored Procedure to get data for the particular field.
I have created a grid view where data is coming from Store Procedure.
One of the GridView fields is LinkButton. So on click of link button it should show all the details of the applicant in a new tab. The page is getting redirected but I am not able to store or pass particular field which is "APPL_REF_NO" as mention in code.
ASP Code
<asp:GridView ID="gvServiceApplication" runat="server" AutoGenerateColumns="false" EmptyDataText="No Data Found"
Width="100%" HeaderStyle-BackColor="#facf5a"
HeaderStyle-ForeColor="Black" RowStyle-BackColor="White"
RowStyle-ForeColor="Black">
<Columns>
<asp:TemplateField HeaderText="ApplicationNo">
<ItemTemplate>
<asp:LinkButton ID="lblApplicationNo" runat="server" Text='<%#Eval("APPL_REF_NO") %>' OnClick="btnApplicantDetails_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
protected void btnApplicantDetails_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(), "OpenWindow", "window.open
('ApplicantDetails.aspx','_blank');", true);
}
private void ApplicationDetailBind()
{
try
{
DataTable dtApplicationDetail = new DataTable();
dtApplicationDetail = objDepartmentWiseBA.getApplicantDetails(applicationnumber).Tables[0];
gvApplicationIndetail.DataSource = dtApplicationDetail;
gvApplicationIndetail.DataBind();
}
catch (Exception)
{
throw;
}
}
We need to show application details based on parameter passed from LinkButton.
This paramters passed will again be used in StoredProcedure to bind another grid in ApplicantDetails Page. Thanks
Use the following line in place of second line in link button click event.
The approach is to pass the desired value as a query string parameter to ApplicationDetails.aspx page. A query string parameter can then be easily obtained using the second code snippet.
Second line in link button click event
this.GetType(), "OpenWindow",
String.Format("window.open('ApplicantDetails.aspx?applRefNo={0}','_blank');", (sender as LinkButton).Text ), true);
Then in your destination page you can use following C# code to get the value of APPL_REF_NO.
Get the value in destination page
var applRefNoValue = Request.QueryString["applRefNo"];
Instead of storing the value in a session variable, I'd suggest to transmit the value as Request parameter to the page that is opened. So you'd have to extend the URL that is called with the refNo of the row:
protected void btnApplicantDetails_Click(object sender, EventArgs e)
{
var refNo = ((LinkButton)sender).Text;
Page.ClientScript.RegisterStartupScript(
this.GetType(), "OpenWindow", "window.open('ApplicantDetails.aspx?ref_no=" + refNo + "','_blank');", true);
}
This approach does not use session state which might result in some hard to track bugs if the user clicks several of the pages. Each detail page that is opened receives the matching reference number.
In the detail page, you can use the Request object to read the parameter and fetch the corresponding data:
var refNo = Request["refNo"];
// ...
use onCommand event with command arguments, check the following code in the page
<asp:LinkButton ID="lblApplicationNo" runat="server"
Text='<%#Eval("APPL_REF_NO") %>'
OnCommand="btnApplicantDetails_Command" CommandName="ApplicantDetails"
CommandArgument='<%#Eval("APPL_REF_NO") %>'></asp:LinkButton>
and the following in the code
protected void btnApplicantDetails_Command(object sender, CommandEventArgs e)
{
string appNo = e.CommandArgument.ToString();
// do work ...
}
Write as below
<Columns>
<asp:TemplateField HeaderText="ApplicationNo">
<ItemTemplate>
<asp:LinkButton ID="lblApplicationNo" runat="server"
data-applRefNo='<%#Eval("APPL_REF_NO") %>' Text = "Application Details" OnClick="btnApplicantDetails_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</columns>
protected void btnApplicantDetails_Click(object sender, EventArgs e)
{
string applRefno = btnApplicantDetails.attr("data-applRefNo");
your coding here
}

How to mark records in gridview as read and unread

This is my GridView1. I want the latest record to be highlighted and after user click the authorization no(which user viewed the record in next page), the row will not be highlighted (means after the user view the record, the row is back to normal, no highlight no bold font).
My current progress is,
I have created new bit field in my database named ReadStatus, and defaulted to 0
Next, I need to do the onrowdatabound coding in order to implement this.
first question is, do i need to read the bit column(ReadStatus) as I read all this column?AuthorizationNo, ProductID,Name,Qty,---(ReadStatus)??
should I read ReadStatus in this code?
/ /READING RECORD FROM TABLE TRACK_ITEM
while (reader.Read())
{
MerchantProduct merchantProduct = new MerchantProduct();
merchantProduct.TxID = reader["TxID"].ToString();
merchantProduct.ProductID = reader["ProductID"].ToString();
merchantProduct.Name = reader["ProductName"].ToString();
merchantProduct.Qty = Convert.ToInt32(reader["Qty"]);
listLatestProduct.Add(merchantProduct);
}
return listLatestProduct;
second is, can anyone show me the proper way to code in onrowdatabound?
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Tried many code here but none is working
}
Thank you.
First you need to add one more column in ur db for ReadStatus(1/0),
then make is as hiddenfield in your aspx page.
<asp:TemplateField HeaderText="ReadStatus" Visible="false">
<ItemTemplate>
<asp:Label ID="readStatus" runat="server"></asp:Label>
<asp:HiddenField ID="readStatusHiddenField" runat="server" Value='<%#Eval("ReadStatus") %>'/>
</ItemTemplate>
</asp:TemplateField>
In your grid rowdataboun, just paste this code.It works for me
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// searching through the rows
if (e.Row.RowType == DataControlRowType.DataRow)
{
int reading = Convert.ToInt32(((HiddenField)e.Row.FindControl("readStatusHiddenField")).Value);
if (reading == 0)
{
e.Row.BackColor = Color.LightGray;
e.Row.Font.Bold = true;
}
}
}

asp.net c# is checkbox checked?

How do I determine if the checkbox is checked or not checked?
Very perplexed why this is not working - it is so simple!
On my web form:
<asp:CheckBox ID="DraftCheckBox" runat="server" Text="Save as Draft?" />
<asp:Button ID="PublishButton" runat="server" Text="Save" CssClass="publish" />
Code behind which runs in the click event for my save button:
void PublishButton_Click(object sender, EventArgs e)
{
if (DraftCheckBox.Checked)
{
newsItem.IsDraft = 1;
}
}
When debugging it never steps into the If statement when I have the checkbox checked in the browser. Ideas?!
I think there maybe some other code affecting this as follows...
In Page_load I have the following:
PublishButton.Click += new EventHandler(PublishButton_Click);
if (newsItem.IsDraft == 1)
{
DraftCheckBox.Checked = true;
}
else
{
DraftCheckBox.Checked = false;
}
newsItem is my data object and I need to set the checkbox checked status accordingly.
When the save button is hit I need to update the IsDraft property based on the checked status of the checkbox:
void PublishButton_Click(object sender, EventArgs e)
{
if (IsValid)
{
newsItem.Title = TitleTextBox.Text.Trim();
newsItem.Content = ContentTextBox.Text.Trim();
if (DraftCheckBox.Checked)
{
newsItem.IsDraft = 1;
}
else
{
newsItem.IsDraft = 0;
}
dataContext.SubmitChanges();
}
}
So, isDraft = 1 should equal checkbox checked, otherwise checkbox should be un-checked. Currently, it is not showing this.
Specify event for Button Click
<asp:Button ID="PublishButton" runat="server" Text="Save" onclick="PublishButton_Click" />
What i can see you have not got a OnClick on your button. So like this:
<asp:CheckBox ID="DraftCheckBox" runat="server" Text="Save as Draft?" />
<asp:Button ID="PublishButton" runat="server" OnClick="PublishButton_Click"
Text="Save" CssClass="publish" />
And then the function should work like it is:
protected void PublishButton_Click(object sender, EventArgs e)
{
if (DraftCheckBox.Checked)
{
newsItem.IsDraft = 1;
}
}
Please replace code as following code..
void PublishButton_Click(object sender, EventArgs e)
{
if (DraftCheckBox.Checked==True)
{
newsItem.IsDraft = 1;
}
}
Try adding onclick="PublishButton_Click" in the button field on the form. And I don't know if it makes a difference, but generated event handlers are protected void.
For me the best solution in the end has been to create 2 separate pages: 1 for editing a news articles & 1 for a new news article. So Ill never then be in the position of a new news data object being created when the page reloads.
Both page return to the article index list page when the save button is pressed and that seems to work with being able to save the state of the draft checkbox and then show the state on the edit page.
The checkbox.checked isn't used in the context you want it to (this is a boolean that if true, will make the checkbox look checked).
What you could do is to use instead a checkboxlist. Then you could do the following:
foreach(Listitem li in CheckBoxList1.Items)
{
if (li.Selected)
{
NewsItem.Isdraft = 1;
}
}

DetailsView not showing

I have a gridview add a link button "Edit":
<asp:LinkButton ID="btnViewDetails" runat="server" text="Edit" CommandName="Select"></asp:LinkButton>
and
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
using (var dataContext = new NewsStandAloneDataContext(Config.StandaloneNewsConnectionString))
{
DetailsView1.ChangeMode(DetailsViewMode.Edit);
DetailsView1.Visible = true;
var dataList =
dataContext.sp_Name(Convert.ToInt32(GridView1.SelectedValue), Value1);
ScriptManager.RegisterStartupScript(this, GetType(), "show1", "openEditWindow();", true);
DetailsView1.DataSource = dataList;
DetailsView1.DataBind();
}
}
But my details view does not show anything.
Looking at your code you have two different methods in play. In your ViewDetails button you are referencing a command name and argument. In your other block of code you are responding to the changing of the selected row. Two different concepts.
You would want to show the details view from the "ItemCommand" event, and not the selectedindexchanged event.

How can I access DataGridRow from a textbox on that row?

In a DataGrid, when text in a textbox changes I want to add the value of another field in that row to an array.
public void txtTitle_TextChanged(object sender, EventArgs e)
{
TextBox titleBox = (TextBox)sender;
DataGridItem myItem = (DataGridItem)titleBox.Parent.Parent;
string test = DataBinder.Eval(myItem.DataItem, "prod_id").ToString();
}
However myItem.DataItem evaluates as null. I was expecting it to evaluate as DataRowView?
You can get the TextChanged event to fire if you do the following:
<asp:DataGrid ID="DataGrid1" runat="server" AutoGenerateColumns="False"
onitemdatabound="DataGrid1_ItemDataBound">
<Columns>
<asp:TemplateColumn HeaderText="Test">
<ItemTemplate>
<asp:TextBox OnTextChanged="txtBox_TextChanged" ID="TextBox1" runat="server" AutoPostBack="True"></asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="Name" HeaderText="Test 1"></asp:BoundColumn>
</Columns>
</asp:DataGrid>
You will notice that i have the following properties set:
AutoPostBack="True"
I have also manually added the OnTextChanged="txtBox_TextChanged" to the text box as well.
In my code behind i have:
protected void txtBox_TextChanged(object sender, EventArgs e)
{
TextBox txtBox = (TextBox)sender;
Label1.Text = txtBox.Text;
}
The only way the event will fire is when you lose focus on the text box after typing.
Key points to consider:
This will cause a post back, so Ajax might be a good way to keep the user experience nice.
You will need to make sure you wrap your DataBind() in a if (!IsPostBack)
Hope this helps!
Effectively, I solved this by adding an autonumber column to the table, and using the value of this to determine the row's positino in the table, then using the value of this to affect the appropriate row in the datagrid.
I'm now merely changing the color of the row rather than adding values in that row to an array, as stated in the original question.
public void txtPrice_TextChanged(object sender, EventArgs e)
{
TextBox txtPrice = (TextBox)sender;
DataGridItem myItem = (DataGridItem)txtPrice.Parent.Parent;
markRows(myItem, true);
}
public void markRows(DataGridItem myItem, bool toSave)
{
// Prepeare to save this record?
CheckBox thisSave = (CheckBox)myItem.FindControl("chkSave");
thisSave.Checked = toSave;
// Establish the row's position in the table
Label sNo = (Label)myItem.FindControl("SNo");
int rowNum = Convert.ToInt32(sNo.Text) - 1;
CheckBox rowSave = (CheckBox)grid.Items[rowNum].FindControl("chkSave");
// Update background color on the row to remove/add highlight
if (rowSave.Checked == true)
grid.Items[rowNum].BackColor = System.Drawing.Color.GreenYellow;
else
{
Color bgBlue = Color.FromArgb(212, 231, 247);
grid.Items[rowNum].BackColor = bgBlue;
// some code here to refresh data from table?
}
}

Categories