gridview commandargument on buttonfield pagination used - c#

I am using c#.net
I have a gridview which needs to contain a 'Use' button (appointmentId set as the commandargument).
Source Code
<asp:GridView ID="resultsReturned" runat="server" AllowPaging="True"
AutoGenerateColumns="False"
EnableSortingAndPagingCallbacks="True"
OnPageIndexChanged="resultsReturned_PageIndexChanged"
onrowcommand="resultsReturned_RowCommand">
<Columns>
<asp:BoundField DataField="UserAppointmentId" HeaderText="App ID" />
<asp:BoundField DataField="UserBookingName" HeaderText="Booking Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server"
ID="UseButton"
Text="Use"
CommandName="Use"
CommandArgument="UserAppointmentId" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-Behind
protected void resultsReturned_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Use")
{
correctAppointmentID.Value = (e.CommandArgument.ToString());
}
}
This is used for the pagination:
private void BindAppointments()
{
var results = appointmentRepos.GetBookingIdBySearchCriteria(catgoryid, resultsReturned.PageIndex * resultsReturned.PageSize, -1);
resultsReturned.DataSource = results;
resultsReturned.DataBind();
}
I am binding the appointments to the gridview within the PageLoad/search_Click
This is the error I am receiving:
Callbacks are not supported on TemplateField because some controls cannot update properly in a callback. Turn callbacks off on 'resultsReturned'.

Try the following:
<asp:Button runat="server"
ID="UseButton" Text="Use" CommandName="Use"
CommandArgument='<%# DataBinder.Eval(Container,"DataItem.UserAppointmentId") %>' />
and Set EnableSortingAndPagingCallbacks="False"

Related

how can i delete a gridview row? while the data is not yet saved in the database

i have a system that adds items into the DataGrid, my question is how can i use the delete button? when the user wants the item deleted, user will press the button to delete the row, but i cant seem to make it work. thank you!
<asp:GridView runat="server" ID="gridview" CssClass="table-hover" AutoGenerateColumns="true" HeaderStyle-BackColor="CornflowerBlue" BackColor="White" BorderWidth="5" BorderColor="CornflowerBlue" OnSelectedIndexChanged="gridview_SelectedIndexChanged" CellPadding="8"
CellSpacing="0" Width="100%" OnRowDeleting="gridview_RowDeleting" EmptyDataText="No records to display">
<HeaderStyle BackColor="CornflowerBlue"></HeaderStyle>
<Columns>
<asp:CommandField ShowDeleteButton="true" ButtonType="Button" />
<asp:TemplateField ItemStyle-Width="25px" HeaderText="">
<ItemTemplate>
<asp:ImageButton ID="lnkEdit" runat="server" ImageUrl="~/Images/Icons/Modify.png" OnClick="Edit" />
<%--<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" OnClick="Edit"></asp:LinkButton>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is my script
<script runat="server">
void gridview_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
TableCell cell = gridview.Rows[e.RowIndex].Cells[2];
}
</script>
grid view picture
In Gridview add OnRowCommand="gridview_RowCommand"
CommandField can work but I go like this:
<asp:TemplateField ItemStyle-Width="25px" HeaderText="">
<ItemTemplate>
<asp:Button ID="lnkDel" runat="server" Text="Delete" CommandName="Del" CommandArgument='<%#Eval("ID")%>' />
</ItemTemplate>
</asp:TemplateField>
In code behind
protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Del") {
//Get Command Argument
int IdToDelete = Convert.ToInt32( e.CommandArgument.ToString());
//Your Delete Command
//Rebind GridView
}
}

how to get the specific row value from corresponding button click in gridview [duplicate]

This question already has answers here:
ASP GridView get row values on button click
(2 answers)
Closed 7 years ago.
I have declared a gridview where some fields are bound from database. I have added a item template where I have got a textbox and button. Now when I click the button, I want to catch the values of a column and that textbox of that corresponding row. How can I get it done?
My aspx gridview markup:
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="FOODITEM_ID" DataSourceID="SqlDataSource2" EnableModelValidation="True" OnSelectedIndexChanged="GridView2_SelectedIndexChanged"
OnRowCommand="GridView2_OnRowCommand">
<Columns>
<asp:BoundField DataField="FOOD_ITEM_NAME" HeaderText="FOOD_ITEM_NAME" SortExpression="FOOD_ITEM_NAME" />
<asp:BoundField DataField="FOODITEM_ID" HeaderText="FOODITEM_ID" ReadOnly="True" SortExpression="FOODITEM_ID" />
<asp:BoundField DataField="PRICE" HeaderText="PRICE" SortExpression="PRICE" />
<asp:BoundField DataField="DAY_AVAILABLE" HeaderText="DAY_AVAILABLE" SortExpression="DAY_AVAILABLE" />
<asp:BoundField DataField="TIME_AVAILABLE" HeaderText="TIME_AVAILABLE" SortExpression="TIME_AVAILABLE" />
<asp:BoundField DataField="DISCOUNT_PERCENTAGE" HeaderText="DISCOUNT_PERCENTAGE" SortExpression="DISCOUNT_PERCENTAGE" />
<asp:BoundField DataField="START_DATE" HeaderText="START_DATE" SortExpression="START_DATE" />
<asp:BoundField DataField="DEADLINE" HeaderText="DEADLINE" SortExpression="DEADLINE" />
<asp:BoundField DataField="Rating" HeaderText="Rating" SortExpression="Rating" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="Add"
Text="Add" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now when I press the the button, how can i get the textbox and other fields' values of that corresponding row.
There are coupe of things you are missing, so I have decided to give you mine complete sample.
First aspx code. Take notice I use CommandNames (Edit, Delete, Cancel, Update) for appropriate command.
Second, I have binded "ItemsGridView_RowUpdating" to catch new values (this is what are you looking for).
<asp:GridView ID="ItemsGridView" runat="server" DataKeyNames="ItemId,FieldName" PageSize="1000"
AutoGenerateColumns="False" AllowPaging="False" AllowSorting="False" SkinID="DefaultGridView"
OnRowEditing="ItemsGridView_RowEditing"
OnRowCancelingEdit="ItemsGridView_RowCancelingEdit"
OnRowDeleting="ItemsGridView_RowDeleting"
OnRowUpdating="ItemsGridView_RowUpdating"
>
<Columns>
<asp:TemplateField ItemStyle-CssClass="TemplateFieldFourColumns">
<ItemTemplate>
<asp:ImageButton ID="ibEdit" runat="server" ToolTip="<% $resources:AppResource,Edit %>" SkinID="EditPage" CommandName="Edit" />
<asp:ImageButton ID="ibDelete" runat="server" ToolTip="<% $resources:AppResource,Delete %>" SkinID="DeletePage" CommandName="Delete" OnClientClick='<%#this.GetDeleteConfirmation() %>' />
<asp:ImageButton ID="ibUp" runat="server" ToolTip="<% $resources:AppResource,Up %>" SkinID="UpPage" OnClick="ibUp_Click" CommandArgument='<%#Eval("ItemId")%>' />
<asp:ImageButton ID="ibDown" runat="server" ToolTip="<% $resources:AppResource,Down %>" SkinID="DownPage" OnClick="ibDown_Click" CommandArgument='<%#Eval("ItemId")%>' />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="ibCancel" runat="server" ToolTip="<% $resources:AppResource,Cancel %>" SkinID="Cancel" CommandName="Cancel" />
<asp:ImageButton ID="ibUpdate" runat="server" ToolTip="<% $resources:AppResource,Save %>" SkinID="Save" CommandName="Update" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="<% $resources:AppResource,Format %>">
<ItemTemplate>
<asp:Label ID="lblFormat" runat="server" Text='<%#Eval("Format")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFormat" runat="server" Text='<%#Bind("Format")%>' Width="50"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Nov code behind:
protected void ItemsGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
ItemsGridView.EditIndex = e.NewEditIndex;
ItemsGridView.DataSource = this.genericForm.FormItems; //TODO: get your data source
ItemsGridView.DataBind();
}
protected void ItemsGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
ItemsGridView.EditIndex = -1;
ItemsGridView.DataSource = this.genericForm.FormItems; //TODO: get your data source
ItemsGridView.DataBind();
}
protected void ItemsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//delete...
try
{
Guid itemId = (Guid)e.Keys[0]; //key
//TODO: delete your item and bind new data
}
catch (Exception ex)
{
this.MessageBoxError(ex);
}
}
protected void ItemsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//update...
try
{
//get your key and read new values for update....
Guid itemId = (Guid)e.Keys[0];
string fieldName = (string)e.Keys[1];
string Format = (string)e.NewValues["Format"];
//TODO: make an update and rebind your data
}
catch (Exception ex)
{
this.MessageBoxError(ex);
}
}
Happy coding!
Flowwing code should work:
void GridView2_OnRowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Add")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = CustomersGridView.Rows[index];
string otherFieldText = row.Cells[0].Text; // put othe fields' index
TextBox txt = (TextBox)row.FindControl("TextBox1"); // Textbox
string txtVal = txt.text; // Textbox value
}
}

CausesValidation="True" But Still Throwing Invalid Postback?

I am using html to create a datagrid and in the syntax for the grid, I have CausesValidation="True" BUT I still get the dreaded
Invalid Postback
This is the code behind and if additional info is needed please let me know as I am pulling my hair out to resolve this issue.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Setup();
GetThing1();
GetThing2();
}
}
private void GetThing1()
{
this.gridInfo.Visible = true;
//Run SQL Query to populate datagrid
this.gridInfo.DataSource = DS;
this.gridInfo.DataBind();
}
protected void gridInfo_ItemCommand(object source, DataGridCommandEventArgs e)
{
if (!Page.IsPostBack)
{
if (e.CommandName == "AlterData")
{
Response.Redirect(".../pages/newpage.aspx");
}
}
}
private void GetThing2()
{
if (userNameType == "Valid")
{
//Run this SQL Procedure
//bind to datagrid
}
else
{
//Run this procedure
//bind to datagrid
}
}
And this is the HTML/CSS used for creating the grid itself
<asp:DataGrid runat="server" ID="gridInfo" AutoGenerateColumns="false" CssClass="DataGrids"
GridLines="Both" ShowFooter="true" OnItemCommand="gridInfo_ItemCommand" OnItemDataBound="gridInfo_ItemDataBound">
<ItemStyle CssClass="row" />
<FooterStyle CssClass="DataGridFooters" />
<HeaderStyle CssClass="DataGridHeaders" />
<Columns>
<asp:TemplateColumn HeaderText="ID" ItemStyle-CssClass="Blue" ItemStyle-HorizontalAlign="Center"
HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="40" Visible="true">
<ItemTemplate>
<asp:LinkButton ForeColor="White" ID="btnEdit" runat="server" CausesValidation="True"
CssClass="BoldTextWhite" CommandName="Edit" Text='<%# Eval("ID") %>' CommandArgument='<%# Eval("ID") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="ID" HeaderText="ID" Visible="false"> </asp:BoundColumn>
<asp:BoundColumn DataField="first name" HeaderText="First"></asp:BoundColumn>
<asp:BoundColumn DataField="last name" HeaderText="Last"></asp:BoundColumn>
</asp:TemplateColumn>
Setup method below....
private void Setup()
{
this.lblMessage.Text = "Please click an ID from the grid for further information";
}
And this message is thrown when I click one of the ids in gridinfo, which should launch a seperate page, not load any data to the grid so I am not sure why this error is displaying.
Need more information, what exactly you are doing when you get this error. Also there is no code for your Setup() method. How is the postback event is fired, have you click on any control on the page?

Checkboxfield value controls button visibility

I have a gridview which displays the contents of a database table in rows. There is a CheckboxField there and a Select button. I want to set button visibility to false when checkboxfield is checked.
this is my aspx page:
<asp:DetailsView ID="DetailsViewERgo" runat="server" Height="50px"
Width="100%" AutoGenerateRows="False" CellPadding="4"
DataSourceID="LinqDataSourceErgo" ForeColor="#333333" GridLines="None"
HeaderText="Σύντομη Περιγραφή Επιλεγμένου Έργου">
<Columns>
<asp:CheckBoxField DataField="Diekperewsi" HeaderText="Answered"
SortExpression="Diekperewsi" Visible="True"
ItemStyle-HorizontalAlign="Center">
<ItemStyle HorizontalAlign="Center" />
</asp:CheckBoxField>
<asp:TemplateField HeaderText="Insert Answer" ShowHeader="False">
<ItemTemplate>
<center>
<asp:Button ID="Button1" runat="server" CausesValidation="False"
CommandName="Select" Text="Επιλογή" Visible="true" >
</asp:Button>
</center>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I have tried this but only works with checkboxes
protected void GridViewAitima_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)e.Row.FindControl("Diekperewsi");
Button b = (Button)e.Row.FindControl("Button1");
if (!cb.Checked)
{
b.Visible = false;
}
else
{
b.Visible = true;
}
}
}
Your code will run on the server side but it looks as if the the AutoPostBack property for your checkbox is not set to true -
AutoPostBack="True"
so when the checkbox is checked the code will not run immediately, it will only run after another event has caused your page to postback.
CheckBoxField has no id thus you can't find it by id, moreover it has no value propertie.
I suggest you use template field just like you used for the button, but instead put a checkbox in it.
so instead of :
<asp:CheckBoxField DataField="Diekperewsi" HeaderText="Answered"
SortExpression="Diekperewsi" Visible="True"
ItemStyle-HorizontalAlign="Center">
<ItemStyle HorizontalAlign="Center" />
</asp:CheckBoxField>
put :
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="Diekperewsi" Enabled="false" Checked='<%#Eval("Diekperewsi")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
and you are good

How to edit an entire column for all rows asp:GridView

So I have google'd and searched stackoverflow, and now my brain is overloaded. I am a novice at asp.net, but getting the hang of it.
My current requirement is to have a gridview where upon load, 1 column for all rows is immediately placed into edit mode. I used this question and code to get me going:
Allowing one column to be edited but not another
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
autogenerateeditbutton="true"
allowpaging="true"
datakeynames="CustomerID"
runat="server">
<columns>
<asp:boundfield datafield="CustomerID" readonly="true" headertext="Customer ID"/>
<asp:boundfield datafield="CompanyName" readonly="true" headertext="Customer Name"/>
<asp:boundfield datafield="Address" headertext="Address"/>
<asp:boundfield datafield="City" headertext="City"/>
<asp:boundfield datafield="PostalCode" headertext="ZIP Code"/>
</columns>
</asp:gridview>
I have searched and found a few good solutions, however, I do not fully understand them and have been unsuccesful at implementing them. They are:
Edit/Update a single GridView field
Put multiple rows of a gridview into edit mode
So my question is, how would you go about placing a column, (e.g, ZIP Code) into edit mode for all rows at the same time?
All help is appreciated!
Thanks!
Stephen
You won't be able to use the built-in edit functionality, but you can achieve this by loading the column in edit mode using a TemplateField:
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" ...>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("SomeColumn") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="SomeOtherColumn" HeaderText="Foo" />
...
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CommandName="Update" CommandArgument='<%# Container.ItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow row = GridView1.Rows[(int)e.CommandArgument];
if (row != null)
{
TextBox txt = row.FindControl("TextBox1") as TextBox;
if (txt != null)
{
//get the value from the textbox
string value = txt.Text;
}
}
}
EDIT: Putting a button outside of the GridView, you would update like this:
<asp:GridView>
...
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Update" OnClick="Button1_Click" />
Code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
TextBox txt = row.FindControl("TextBox1") as TextBox;
if (txt != null)
{
//get the value from the textbox
string value = txt.Text;
}
}
}

Categories

Resources