Grid view row updating and deleting - asp.net

I have a grid view with below markup and below datasourse (linq query-stored procedure), I have added delete and update command field, but I do not know what code I have to add until deleting and updating for this grid view works.
<asp:GridView ID="GridViewDocuments_Search" runat="server" AutoGenerateColumns=False Visible="False" onrowcommand="GridViewDocuments_Search_RowCommand"
DataKeyNames="DocID" PageSize="100" >
<Columns>
<asp:TemplateField HeaderText = "Details">
<ItemTemplate>
<asp:Button ID ="btn_Show" Text="Details" runat= "server" CommandName= "Details" CommandArgument='<%#
Container.DataItemIndex%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:HyperLinkField DataNavigateUrlFields="Docid,Transid"
DataNavigateUrlFormatString="~/DocResult.aspx?Docid={0}&TransID={1}"
DataTextField="DocumentNo" HeaderText="Doc" />
<asp:BoundField DataField="title" HeaderText="Title" SortExpression="title" />
<asp:BoundField DataField="transmittal" HeaderText="transmittal" SortExpression="transmittal" />
<asp:BoundField DataField="Docid" HeaderText="Docid" Visible="false" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
protected void btnSearch_Click(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
var query = _DataContext.spQuickSearch(txtSearchKeywords.Text);
GridViewDocuments.Visible = false;
GridViewDocuments_Search.Visible = true;
GridViewDocuments_Search.DataSource = query;
GridViewDocuments_Search.DataBind();
}
The stored procedure spQuickSearch is like below:
ALTER proc [dbo].[spQuickSearch]
#Searchtext varchar(50)=null
AS
select DocId,TransId,DocumentNo,Title,TRANSMITTAL
from DocumentSum2
where DocumentNo like '%'+#SearchText + '%'
or Title like '%'+#SearchText + '%'
or TRANSMITTAL like '%'+#SearchText + '%'

You can handle commands like this:
protected void GridViewDocuments_Search_RowCommand(object sender, GridViewCommandEventArgs e)
{
string cmdArg = e.CommandArgument.ToString();
switch (e.CommandName)
{
case "Details":
//TODO: handle your Details command...
break;
case "Delete":
//TODO: handle your Delete command...
break;
}
}
You can add as many commands as you want (CommandName property for control). For example you can add another button and set Delete CommandName like this:
<asp:Button ID ="btn_Delete" Text="Delete" runat= "server" CommandName= "Delete" CommandArgument='<%#
Container.DataItemIndex%>' />
After command is completed you can call DataBind to refresh grid:
GridViewDocuments_Search.DataBind();

check this example
http://www.vkinfotek.com/gridview/gridview-commandfield.html
for detail
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.commandfield.showeditbutton.aspx

Related

Unable to get selected item of dx:ASPxListBox on ASPxGridView_Updating event of devexpress control

I have used dx:ASPxGridView where I have one dx:GridViewDataTextColumn with EditItemTemplate which contain dx:ASPxListBox. When I click on update command I am not able to get selected items of dx:ASPxListBox under ASPxGridView_Updating.
<dx:ASPxGridView
ID="ASPxGridView"
runat="server"
AutoGenerateColumns="False"
DataSourceID="TradersDS"
KeyFieldName="TraderId">
<SettingsEditing Mode="PopupEditForm" PopupEditFormWidth="600px" />
<ClientSideEvents RowDblClick="function(s, e)
{
s.StartEditRow(e.visibleIndex);
}"
EndCallback="PrepareGridViewForNewDesing" Init="PrepareGridViewForNewDesing" />
<Columns>
....
<dx:GridViewDataTextColumn FieldName="CounterParty" VisibleIndex="3">
<EditItemTemplate>
<dx:ASPxListBox ID="lstCounterParty" runat="server" SelectionMode="CheckColumn" EnableSelectAll="true"
Width="285"
Height="300"
DataSourceID="CounterPartiesDS"
ValueField="ID"
ValueType="System.String"
TextField="Name">
<%-- <ClientSideEvents SelectedIndexChanged="function(s, e) {lbModels.PerformCallback('1');}" />--%>
</dx:ASPxListBox>
</EditItemTemplate>
</dx:GridViewDataTextColumn>
...
</Columns>
</dx:ASPxGridView>
C# Code..
protected override void ASPxGridView_Updating(object sender, ASPxDataUpdatingEventArgs e)
{
var gridView = sender as ASPxGridView;
GridViewDataColumn list = gridView.Columns["CounterParty"] as GridViewDataColumn;
var counterPartyListBox = (ASPxListBox)gridView.FindEditRowCellTemplateControl(list, "lstCounterParty");
string selectedItemsAsString = string.Empty;
foreach (ListEditItem item in counterPartyListBox.SelectedItems)
selectedItemsAsString += item.Value + ";";
base.ASPxGridView_Updating(sender, e);
}
Here I always get count 0 of SelectedItems. On addition to this My devExpress control version are 9.3.3
What is wrong with this code any help , guidance really appreciated.
Make sure that you set the ASPxListBox.ValueType property to the corresponding .NET type that matches the type of the "ValueField" column.
May be, according to the (ValueField="ID"), the (ASPxListBox.ValueType) should be numeric? (System.Int32, etc.)

Remove TemplateField during page load or before databind

I want to remove templatefield from gridview during pageload or before databind to GridView. I have 2 data sources for retrieving data. The data retrieved from one of the data sources do not have the columns ExpireDate and ExpireDays.
So I want to delete the templatefields corresponding to ExpireDate and ExpireDays if the GridView is populated from the data source that do not have those 2 fields.
Setting the visibility to false still will have error of DataRowView doesn't contain property name ExpireDate and ExpireDays.
Markup
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ID" HeaderText="No."/>
<asp:BoundField DataField="Name" HeaderText="Name"/>
<asp:BoundField DataField="CourseName" HeaderText="Course Enroll" />
<asp:BoundField DataField="SubMember" HeaderText="ChildMember" />
<asp:TemplateField HeaderText="Expiry Days">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label runat="server" ID="expDsL" Text=' <%# Eval("ExpiryDays") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Expiry On">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label runat="server" ID="expDeL" Text=' <%# Eval("ExpiryDate") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Function">
<ItemStyle HorizontalAlign="Center" Width="100px"></ItemStyle>
<ItemTemplate>
<asp:ImageButton ImageUrl="~/Images/editB.gif" ID="btnEdit" runat="server" ToolTip="Edit" CommandName="Edit" CommandArgument='<%# Eval("ID") %>' />
<asp:ImageButton ImageUrl="~/Images/delB.gif" ID="btnDelete" runat="server" ToolTip="Delete" CommandName="Delete" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if(Class.ToLower() != "classAA")
{
// using naveen answer can remove the column.
var expiryDateF = ((DataControlField)GridView1.Columns.Cast<DataControlField>().Where(fid => fid.HeaderText == "Expiry Days").SingleOrDefault());
var expiryDaysF = ((DataControlField)GridView1.Columns.Cast<DataControlField>().Where(fid => fid.HeaderText == "Expiry On").SingleOrDefault());
if (expiryDateF != null)
{
GridView1.Columns.Remove(expiryDateF);
}
if (expiryDaysF != null)
{
GridView1.Columns.Remove(expiryDaysF);
}
}
if(!this.IsPostBack)
{
BindData();
}
}
protected void SaveMember(object sender, EventArgs e)
{
//getting member information and perform checking.
bool success = dbbb.AddMem(memberdetails);
if(success == true)
{
BindData();
}
else
{
//prompt fail message.
}
}
protected void BindData()
{
DataTable dt = dbbb.RetrieveList();
if(dt != null)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton btnDel = (ImageButton)e.Row.FindControl("btnDelete");
btnDel.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this member?')");
}
}
How could I delete the column?
Two methods to achieve this
Method 1 - Remove by Index
if(!table.Columns.Contains("CustomerID1"))
{
//seven is the column index here. ie, 8th column
CustomersGrid.Columns.RemoveAt(7);
}
Method 2 - Remove using Columns Header Text
var expiryDateField= ((DataControlField)CustomersGrid.Columns
.Cast<DataControlField>()
.Where(fld => fld.HeaderText == "Expiry Date")
.SingleOrDefault());
if(expiryDateField != null)
{
CustomersGrid.Columns.Remove(expiryDateField);
}
Please not that
CustomersGrid is the name of the asp:GridView here.
table is the DataTable that acts as the DataSource of the GridView
The code should be called before DataBind of the GridView
Attach to the rowDataBound event of the grid, there you can set it dynamically.
You have to know the datasource name of the field you want to hide,
for example the headertext for the cell is "SomeHeader", but the databoundfield name for that cell is
"SomeOtherName"
then you have to check it like this (debug through GetColumnIndexByName) and
check the value of
((BoundField)cell.ContainingField).DataField
int GetColumnIndexByName(GridViewRow row, string columnName)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is BoundField)
if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
break;
columnIndex++; // keep adding 1 while we don't have the correct name
}
return columnIndex;
}
remember that the code above will use a BoundField... then use it like:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = GetColumnIndexByName(e.Row, "SomeOtherName");
string columnValue = e.Row.Cells[index].Text;
}
}

pass UNiqueIdentifier to another asp.net page

I have coded this page
I need to pass the uniqueidentifier to another page, i have try these ways :
e.Row.Cells[1].Text = "<a href='Clientes.aspx?UserName='>" + e.Row.Cells[0].Text + "</a>";
and this
Response.Redirect("~/Clientes.aspx?Nome=" + e.Row.Cells[0].Text);
what the best and secure way to pass the GUID to another page ???
Thanks
Alejandro Carnero
In the codebehind of your first page, store the unique identifier in a Session variable, and then redirect to the "Clients" page normally:
Session["myUniqueID"] = e.Row.Cells[0].Text;
Response.Redirect("~/Clientes.aspx");
Then, in the codebehind of "Clientes.aspx", retreive it:
protected void Page_Load(object sender, EventArgs e)
{
string myUniqueID = Session["myUniqueID"].ToString();
}
Note: I use "Page_Load" as an example, you could put this code in whatever method you want.
I have solved this way , source page :
<tr>
<td colspan="3">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns ="False"
CellPadding="4" ForeColor="#333333" GridLines="None" Width="770px" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:HyperLinkField Text="Mostrar Cadastro" DataNavigateUrlFields="idcliente"
DataNavigateUrlFormatString="~/Clientes.aspx?ID={0}"
/>
<asp:BoundField DataField="idcliente" HeaderText="ID" />
<asp:BoundField DataField="nome" HeaderText="Nome" />
<asp:BoundField DataField="endere" HeaderText="Endereço" />
<asp:BoundField DataField="Tel" HeaderText="Telefone" />
<asp:BoundField DataField="pedido" HeaderText="Pedido" />
Destiny page :
protected void Page_Load(object sender, EventArgs e)
{
LblIDCliente.Text = Request.QueryString["ID"];
}

GridView Delete Not Re-Binding

I have a GridView with a delete template field:
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:GridView ID="gvCurrentDay" CssClass="gridview" OnRowCommand="gvCurrentDay_RowCommand" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:BoundField DataField="ClientName" HeaderText="Client" />
<asp:BoundField DataField="ProjectTitle" HeaderText="Project" />
<asp:BoundField DataField="TimeToAdd" HeaderText="Time Allocated" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="imbDeleteRow" ImageUrl="~/images/icons/DeleteRed.png" CommandArgument='<%# Eval("RecordID") %>' CommandName="Delete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
The code runs when the button is pressed and the database entry is removed from the database, but the GridView is not rebinding, here is the code that controls the delete:
protected void gvCurrentDay_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int RecordID = Convert.ToInt32(e.CommandArgument);
tdl objTdl = new tdl();
objTdl.DeleteEntryForDay(RecordID);
GetItineryForDay(Convert.ToDateTime(txtCalendar.Text));
lblMessages.Text = "Entry removed";
}
}
And here is the first part of the GetItineryForDay procedure:
protected void GetItineryForDay(DateTime SelectedDate)
{
gvCurrentDay.DataSource = null;
gvCurrentDay.DataBind();
tdl objTdl = new tdl();
DataTable dt = objTdl.GetUsersProjectTimeForDay(SelectedDate, Convert.ToInt32(Request.Cookies["staffid"].Value));
if (dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
int TotalTime2 = Convert.ToInt32(row[7]);
string TotalTime = row[7].ToString() + " minutes";
gvCurrentDay.DataSource = dt;
gvCurrentDay.DataBind();
Can you see from the code any reason why the GridView is not updating? The GridView sits in an UpdatePanel.
Instead of using "Delete" as the CommandName, use something else, like "ManualDelete". "Delete" is usually trapped by RowDeleting and RowDeleted events.
Alternatively, and since "the database entry is removed from the database", you could put your rebind code in the RowDeleted event.
protected void gvCurrentDay_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
GetItineryForDay(Convert.ToDateTime(txtCalendar.Text));
lblMessages.Text = "Entry removed";
}

Unable to access the checkbox for Serverside coding

Below is my gridview ,
<asp:GridView ID="gridview1" AutoGenerateColumns="False" runat="server"
EnableModelValidation="True" >
<Columns>
<asp:CommandField ButtonType="Link" HeaderText="Delete" InsertImageUrl="~/_layouts/images/TBS.WebParts/Button-Delete-icon.png" ShowDeleteButton="true"/>
<asp:BoundField HeaderText ="Size" DataField="FileSize" />
<asp:BoundField HeaderText ="File" DataField="Size" />
<asp:TemplateField HeaderText="SupportIncluded">
<ItemTemplate>
<asp:CheckBox ID="Checkbox1" runat="server" Checked="false" />
</ItemTemplate>
Now on server side i want to check if the checkbox is checked or not on Submit button click event.
private void btnSubmit_Click(object sender, EventArgs e)
{
if (IsValidPost())
{
bool flag = false;
for( int i=0; i < gridview1.Rows.Count ; i++)
{
if(dgdUpload.Rows[i].FindControl("Checkbox1"),CheckBox).Checked) erorr here...I also tried ....if(Checkbox1.checked)...but unable to access Checkbox1..it says it does not exist in the current context....
flag = true;
}
if(flag)
{
}
}
}
You need to access not only the row but also the template field control. Another option is to develop your own recursive version of FindControl that does a search on the whole tree and not just on one level.
Something like:
dgdUpload.Rows[i].Controls[5].FindControl("Checkbox1")
if I counted the columns in your gridview correctly 5 should be the index of the template field.

Resources