I am a beginner of Asp.net, making l small project but having big problems, :) ...
Right now I have a situation, I used gridview to retrieve data from Access database and I done that, I added buttons in grid view. When I click on button the following error comes
Server Error in '/E Shop' Application. Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page
EnableEventValidation="true" %> in a page. For security purposes,
this feature verifies that arguments to postback or callback events
originate from the server control that originally rendered them. If
the data is valid and expected, use the
ClientScriptManager.RegisterForEventValidation method in order to
register the postback or callback data for validation.
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Width= "100%" CellPadding="3">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table class="style17" width="100%" border=" 0">
<tr>
<td height="100%" width="25%">
<asp:Image ID="Image6" runat="server" Height="144px"
ImageUrl='<%# "data:image/jpg;base64, " + Convert.ToBase64String((byte[]) Eval("Picture")) %>'
Width="158px" BorderColor="Black" BorderStyle="Inset" BorderWidth="1px" />
</td>
<td align="center" height="100%" width="75%">
<table align="right" class="style17">
<tr>
<td align="left">
<asp:Label ID="Label7" runat="server" style="font-size: 15pt; color: #0000FF"
Text='<%# Bind("Title") %>'></asp:Label>
</td>
<td>
<asp:Label ID="Label6" runat="server" Text='<%# Bind("Brand") %>'
CssClass="style18" Font-Size="15pt"></asp:Label>
</td>
<td align="right">
<asp:ImageButton ID="ImageButton1" runat="server" Height="51px"
ImageUrl="~/Images/orange_addtocart-trans.png" Width="159px"
onclick="ImageButton1_Click" />
</td>
</tr>
<tr>
<td align="left">
<strong>Rs:</strong><asp:Label ID="Label2" runat="server"
Text='<%# Bind("Price") %>' CssClass="style18" Font-Size="15pt"></asp:Label>
</td>
<td>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Color") %>'
CssClass="style18" Font-Size="15pt"></asp:Label>
</td>
<td align="right">
<asp:ImageButton ID="ImageButton2" runat="server" Height="51px"
ImageUrl="~/Images/orange_addtocart-trans.png" Width="159px"
onclick="ImageButton2_Click" />
</td>
</tr>
<tr>
<td align="left">
<asp:Label ID="Label4" runat="server" Text='<%# Bind("Condition") %>'
CssClass="style18" Font-Size="15pt"></asp:Label>
</td>
<td>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("Material") %>'
CssClass="style18" Font-Size="15pt"></asp:Label>
</td>
<td>
</td>
</tr>
</table>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<table class="style17">
<tr>
<td align="left" height="100%" width="30%">
<asp:Image ID="Image5" runat="server" Height="144px"
ImageUrl='<%# "data:image/jpg;base64, " + Convert.ToBase64String((byte[]) Eval("Picture")) %>'
Width="193px" />
</td>
<td>
</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>
c#
public partial class Shirts : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source =" + Server.MapPath("~\\App_Data\\Products.mdb"));
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "select * from Shirts";
cmd.Connection = con;
OleDbDataAdapter Adaptor = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
Adaptor.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
// Session["Title"] = "Label7.Text";
}
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
// Response.Redirect("Cart.aspx");
}
protected void Button1_Click(object sender, EventArgs e)
{
// Response.Redirect("Cart.aspx");
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Cart.aspx");
}
}
Please Help me to make the buttons work
Thanks in Advance
You can't create an event handler for controls present in Gridview control like this, because they are not static and they repeat for each item coming from the datasource for the Gridview.
When a button is clicked in Gridview, RowCommand event is raised, so you need to write your logic in this event by identifying your control, something like this:-
To identify each control individually in Gridview RowCommand event, you need to add CommandName & CommandArgument properties to your control:-
<asp:ImageButton ID="ImageButton1" runat="server" Height="51px" ImageUrl="~/Images/orange_addtocart-trans.png" Width="159px" OnCommand="Foo" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
Here, CommandName is used to identify the control which raised the event and CommandArgument is used to identify the current row.
Finally, you can read them in code behind like this:-
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Foo")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
// Add you logic here
}
}
I follow the Example you provide, i set commandname and commandargument properties and in Rowcommand event i try to same steps like example but again i got that Error
Server Error in '/E Shop' Application.
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Source:
<asp:ImageButton ID="ImageButton1" runat="server" Height="51px"
commandname="Foo" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
ImageUrl="~/Images/orange_addtocart-trans.png" Width="159px"
onclick="ImageButton1_Click2"/>
C#
public partial class raff : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source =" + Server.MapPath("~\\App_Data\\Products.mdb"));
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "select * from Shirts";
cmd.Connection = con;
OleDbDataAdapter Adaptor = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
Adaptor.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowCommand(object sender,
GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
// Retrieve the row index stored in the
// CommandArgument property.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button
// from the Rows collection.
GridViewRow row = GridView1.Rows[index];
// Add code here to add the item to the shopping cart.
Response.Redirect("Cart.aspx");
}
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
// Session["Title"] = "Label7.Text";
}
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
// Response.Redirect("Cart.aspx");
}
protected void Button1_Click(object sender, EventArgs e)
{
// Response.Redirect("Cart.aspx");
}
protected void Button2_Click(object sender, EventArgs e)
{
// Response.Redirect("Cart.aspx");
}
protected void Button1_Click1(object sender, EventArgs e)
{
Response.Redirect("Cart.aspx");
}
Related
I have an asyncfileupload control and a repeater that I would like to use to show list of added files. On FileUploadedComplete event I add the new file's name and size to a data table and use it to bind the repeater. I can select a file and add it (SaveAs()), add the info to data table (I can see it is there) but after calling repeater's databind() nothing happens, can't see the file data.
This is what I have (watered down version):
<asp:UpdatePanel runat="server" ID="upnlFU">
<ContentTemplate>
<ajaxToolkit:AsyncFileUpload
runat="server"
ID="fuAttchedDocs"
ThrobberID="myThrobber"
UploaderStyle="Modern"
onuploadedcomplete="fuAttchedDocs_UploadedComplete"
onuploadedfileerror="fuAttchedDocs_UploadedFileError" />
<asp:Repeater runat="server" ID="rptAttachments">
<HeaderTemplate>
<table>
<tr>
<td>File Name</td>
<td>File Size</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("FileName")%></td>
<td><%# Eval("FileSize")%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
Code behind:
DataTable dtAttachments;
protected void Page_Load(object sender, EventArgs e)
if (!Page.IsPostBack)
{
dtAttachments = new DataTable();
dtAttachments.Columns.Add("FileName", Type.GetType("System.String"));
dtAttachments.Columns.Add("FileSize", Type.GetType("System.Int32"));
dtAttachments.AcceptChanges();
}
else
{
dtAttachments = (DataTable)ViewState["Attachments"];
}
BindAndSaveAttachmentData();
}
void BindAndSaveAttachmentData()
{
ViewState["Attachments"] = dtAttachments;
rptAttachments.DataSource = dtAttachments;
rptAttachments.DataBind();
}
protected void fuAttchedDocs_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
{
string sFileName = fuAttchedDocs.FileName;
string sFileSize = e.FileSize;
fuAttchedDocs.SaveAs(FilePath.TEMP_FOLDER + sFileName); // Saving to d:\blah\yada temporary folder
dtAttachments.Rows.Add(new object[] { sFileName, int.Parse(sFileSize) });
BindAndSaveAttachmentData();
}
Both file upload and repeater are inside an update panel.
i have this code:
protected void Button1_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection(GetConnectionString());
{
System.Data.SqlClient.SqlCommand cmd;
sc.Open();
cmd = new System.Data.SqlClient.SqlCommand("SET IDENTITY_INSERT Zapas OFF INSERT INTO Zapas (Zapas.Sezona,.....)SELECT Zapas.Sezona,... FROM Zapas WHERE ID_zapas=#ID;", sc);
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#ID", System.Data.SqlDbType.Text)).Value = (TextBox)ListView1.FindControl("box1");
cmd.ExecuteNonQuery();
sc.Close();
Response.Redirect("~/Zapasy_seznam.aspx");
}
}
I need take value ID from listview, but with this code I have this error:
...expects the parameter '#ID', which was not supplied....
This part of my listview...
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID_zapas" DataSourceID="SqlDataSource1" style="text-align: center ">
<AlternatingItemTemplate>
<tr style="background-color: #e9ffe9;color: #284775;text-align:center">
<td>
<asp:TextBox ID="box1" runat="server" Text='<%# Eval("ID_zapas") %>' Visible="false" />
...
<td style="width:50px;background-color:white">
<asp:LinkButton ID="Button1" runat="server" OnClick="Button1_Click" Visible='<%# HttpContext.Current.User.IsInRole("admin") %>' CausesValidation="False" OnClientClick="javascript: return confirm('Opravdu chcete zápas zkopírovat?');">
<asp:Image ID="Image2" runat="server" ImageUrl="~/Icons/copy.png" Width="29px" Height="29px" ToolTip="Zkopírovat zápas" />
</asp:LinkButton>
</td>
</tr>
</AlternatingItemTemplate>
Have you some idea?
As per comments, please try this:
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
var box1 = (TextBox)((LinkButton)sender).Parent.FindControl("box1");
using (var sc = new SqlConnection(GetConnectionString()))
{
using (var cmd = sc.CreateCommand())
{
sc.Open();
cmd.CommandText = "SET IDENTITY_INSERT Zapas OFF INSERT INTO Zapas (Zapas.Sezona,.....)SELECT Zapas.Sezona,... FROM Zapas WHERE ID_zapas=#ID;";
cmd.Parameters.AddWithValue("#ID", box1.Text);
cmd.ExecuteNonQuery();
sc.Close();
Response.Redirect("~/Zapasy_seznam.aspx");
}
}
}
When using data-aware controls such as a ListView here, the controls are created with automatic unique IDs per data item. This means that you can have more than 1 of the same control (such as "box1" in this case) within the page that should be referenced by the data item (((LinkButton)sender).Parent which is ListViewDataItem, representing the row).
ListViewDataItem.FindControl will find controls of a specific server ID within its own child scope, allowing you to get values for controls within the same row of the button that is being clicked.
<form>
<asp:Repeater id="rptComments" runat="server">
<HeaderTemplate>
<table class="detailstable FadeOutOnEdit">
<tr>
<th style="width:200px;">Answers</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<th style="width:200px;"><asp:DropDownList ID="dropDownForChecklistAnswers" runat="server" /></th>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
<asp:Button id="button" text="Submit" OnClick="Page_Load" runat="server" />
</FooterTemplate>
</asp:Repeater>
</form>
Code Behind:
List<Checklist_Record_Choice> CLRC =
(from choice in db.Checklist_Record_Choices
select choice).ToList();
dropDownForChecklistAnswers.DataSource = CLRC;
DropDownList1.DataTextField = Text;//Text being the name of column2 in the table (which contains yes, no, n/a)
dropDownForChecklistAnswers.DataBind();
ERROR: dropDownForChecklistAnswers does not exist in the current context???
please advise
EDIT;
thanks for reply. I have
public void OnReptDataBound(object sender, RepeaterItemEventArgs e)
{
ClarkeDBDataContext db1 = new ClarkeDBDataContext();
List<string> CLRC =
(from choice in db1.Checklist_Record_Choices
select choice.Text).ToList();
DropDownList ddl = (DropDownList)e.Item.FindControl("dropDownForChecklistAnswers");
ddl.DataSource = CLRC;
}
but DropDownList ddl is coming back as object ref not set to instance of an object...why is it null??
You need to use FindControl to access a control which is part of a Repeater's template.
Subscribe to the OnItemDataBound of the Repeater (set the attribute OnItemDataBound="OnReptDataBound")
And then in your code behind do the following
void OnReptDataBound(object sender, RepeaterItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item)
{
DropDownList ddl = (DropDownList )e.Item.FindControl("dropDownForChecklistAnswers");
ddl.DataSource = ....
im new to asp.net.. please bear with me if ma question is way too trivial!!! :)
im using an accordian control within an update panel. and i also have a button to save some data frm the accordian control! - This complete is a user control which is used in another .aspx page.
now in the page_load event of the user control i initialize my database connection which works absolutely fine while loading data to the accordian.. but when i click on save, in the save button click even handler the database connection object is always null..!! (even though it is initialized in the page_load) please help..
.ascx is as here:
<asp:UpdatePanel ID="PrefPanel" runat="server" >
<ContentTemplate>
<ajaxToolkit:Accordion ID="PrefAccordion" runat="server" HeaderCssClass="accordionHeader"
HeaderSelectedCssClass="accordionHeaderSelected" ContentCssClass="accordionContent"
BackColor="#E8EAF7" Height="530px" Width="500px" AutoSize="None" RequireOpenedPane="false"
BorderStyle="Solid" BorderWidth="1" BorderColor="Black">
<Panes>
<ajaxToolkit:AccordionPane ID="ProjCategoryPaneID" runat="server">
<Header > Project Category</Header>
<Content>
<asp:Panel ID="ProjCategoryPanel" runat="server" Width="100%">
<table align="center" width="100%">
<tr></tr>
<tr>
<td align="left">
<asp:CheckBoxList RepeatDirection="Vertical" TextAlign="Left" ID="ProjCategoryItem1" runat="server" AutoPostBack="false" CausesValidation="false" />
</td>
</tr>
</table>
</asp:Panel>
</Content>
</ajaxToolkit:AccordionPane>
<asp:Button ID="btnSavePref" CssClass="buttonsmall" runat="server" Text="Save" Width="60px" OnClick="btnSavePref_Click"/>
<asp:Button ID="btnCancelPref" CssClass="buttonsmall" runat="server" Text="Cancel" Width="60px" />
</ContentTemplate>
</asp:UpdatePanel>
the code behind is as here:
public partial class UserPreferences : System.Web.UI.UserControl
{
private EAReportingDAL m_DataAccessLayer = null;
// Projects Category
Panel projectCategoryPanel;
CheckBoxList projectCategoryList;
protected void Page_Load(object sender, EventArgs e)
{
String connectionString = WebConfigurationManager.ConnectionStrings ["BSCDB"].ConnectionString;
m_DataAccessLayer = new EAReportingDAL(connectionString);
LoadUserPreferences();
}
protected void btnSavePref_Click(object sender, EventArgs e)
{
string userName = this.Page.User.Identity.Name;
DataSet availabeData = m_DataAccessLayer.GetUserPreferences(this.Page.User.Identity.Name, Constants.ProjectsUIView);
}
}
in the button click event handler btnSavePref_Click() the the db connection object m_DataAccessLayer is always null, but whereas the same object in LoadUserPreferences() [which i haven't pasted here though] works fine! plz guide me where im wrong or if someone needs more details!!
I'm not very familiar with UpdatePanel mechanics but maybe you defined it in such a way that it bypass the Page_Load method.
What I suggest is moving the code create the data access layer to separate method then calling this method from both the page load and button click handler:
private void InitDataAccess()
{
//ignore if already created
if (m_DataAccessLayer != null)
return;
String connectionString = WebConfigurationManager.ConnectionStrings ["BSCDB"].ConnectionString;
m_DataAccessLayer = new EAReportingDAL(connectionString);
LoadUserPreferences();
}
protected void Page_Load(object sender, EventArgs e)
{
InitDataAccess();
}
protected void btnSavePref_Click(object sender, EventArgs e)
{
InitDataAccess();
string userName = this.Page.User.Identity.Name;
DataSet availabeData = m_DataAccessLayer.GetUserPreferences(this.Page.User.Identity.Name, Constants.ProjectsUIView);
}
I know I've done something like this before, but I have no idea why it isn't working now. I have a ListView with some textboxes. I want to read the text out of those boxes when I click a button (linkbutton, whatever).
<asp:ListView runat="server" ID="lv_bar" EnableViewState="true">
<LayoutTemplate>
<table>
<tr>
<th>Foo</th>
</tr>
<tr runat="server" id="itemPlaceholder"></tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><asp:LinkButton ID="lb_delete" CausesValidation="false" runat="server" Text="Del" /></td>
<td><asp:TextBox id="txt_foo" runat="server" /></td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:LinkButton ID="lb_add" CausesValidation="false" runat="server" Text="Add" />
And then here's the relevant code-behind stuff:
protected void Page_Load(object sender, EventArgs e)
{
lb_chapter_add.Click += lb_chapter_add_Click;
if (!IsPostBack)
{
lv_chapters.DataSource = new List<Foo>() { new Foo() { Name = "harbl"} };
lv_chapters.DataBind();
}
}
void lb_add_Click(object sender, EventArgs e)
{
foreach (ListViewDataItem item in lv_bar.Items)
{
var txt_foo = (TextBox)item.FindControl("txt_foo");
Response.Write("foo: " + txt_foo.Text);
}
Response.Write("<br />the end");
Response.End();
}
But what I see when I enter some text into txt_foo and click lb_add is just "the end". What am I doing wrong here?
The problem it that you are using a a non persistent object as DataSource.
Due to clicking the button, you generate a postback and lv_chapters does not contain any items. Set a breakpoint in the line where the foreach is and you will see that lv_chapters.Items in null, or that it's Count property returns 0.