row updating in gridview not working - c#

Gridview update is not happening after I edit it. Used breakpoints and checked, its showing the same existing values which is there before editing. I am not getting any kind of error. Have used Store Procedure to update the Gridview. Please go through the code and help me sort out this problem.
aspx code
<asp:GridView ID="gvData" runat="server" AutoGenerateColumns="False"
OnRowEditing="gvData_RowEditing"
OnRowDataBound="gvData_RowCreated"
OnRowCreated="gvData_RowCreated"
OnRowCancelingEdit="gvData_RowCancelingEdit"
OnRowUpdating="gvData_RowUpdating"
Style="text-align: center; margin-left: 0px;" Height="160px"
Width="657px" BackColor="#DEBA84" BorderColor="#DEBA84"
orderStyle="None" BorderWidth="0px" CellPadding="3" CellSpacing="2"
DataKeyNames="BtnID" Font-Names="Calibri" ForeColor="#CC3300"
EmptyDataText="No Records Found!!!"
CaptionAlign="Left" HorizontalAlign="Left"
>
<AlternatingRowStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" BorderStyle="None" />
<Columns>
<asp:TemplateField HeaderText="BtnID" >
<ItemTemplate>
<asp:Label ID="lblBtnID" runat="server" ForeColor="#003366"
Font-Names="Calibri" Font-Size="Small" Height="24px" Width="20px"
Text='<%#Eval("BtnID") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LogdInUsername" >
<ItemTemplate>
<asp:Label ID="lblLogdInUsername" runat="server" ForeColor="#003366"
Font-Names="Calibri" Font-Size="Small" Height="24px" Width="20px"
Text='<%#Eval("LogdInUsername") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Year">
<ItemTemplate>
<asp:Label ID="lblYear" runat="server" ForeColor="#003366"
Font-Names="Calibri" Font-Size="Small" Height="24px" Text='<%# Eval("Year") %>' Width="20px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Month">
<ItemTemplate>
<asp:Label ID="lblMonth" runat="server" ForeColor="#003366"
Font-Names="Calibri" Font-Size="Small" Text='<%# Eval("Month") %>' Height="24px" Width="20px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comments">
<ItemTemplate>
<asp:Label ID="lblComments" runat="server"
ForeColor="#003366" Font-Names="Calibri" Text='<%# Eval("Comments") %>' Font-Size="Small" Height="24px"
Width="20px" ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TxtComments" runat="server"
Width="300px" Text='<%# Bind("Comments") %>' ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False"
BorderStyle="None" />
<EmptyDataRowStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" />
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" HorizontalAlign="Left"
VerticalAlign="Middle" Wrap="False" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White"
HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" />
<SortedAscendingCellStyle BackColor="#FFF1D4" HorizontalAlign="Left"
VerticalAlign="Middle" Wrap="False" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
cs code
protected void Page_Load(object sender, EventArgs e)
{
DTO objc = new DTO();
string str = Environment.UserName;
GrdGetComments();
if (!IsPostBack)
{
GetYear();
GetMonth();
GrdGetComments();
UserPrincipal up1 = GetUserPrincipal(str);
Session["Username"] = str;
Session["Name"] = up1.Name;
LblName.Text = Session["Username"].ToString();
objc.Name = LblName.Text;
LblLogdInUsername.Text = Session["Name"].ToString();
objc.LogdInUsername = LblLogdInUsername.Text;
LblDateTime.Text = DateTime.Now.ToString();
LblCompany.Text = "";
objc.Company = LblCompany.Text;
}
}
public static UserPrincipal GetUserPrincipal(String userName)
{
UserPrincipal up = null;
PrincipalContext context = new PrincipalContext(ContextType.Domain);
up = UserPrincipal.FindByIdentity(context, userName);
if (up == null)
{
context = new PrincipalContext(ContextType.Machine);
up = UserPrincipal.FindByIdentity(context, userName);
}
if (up == null)
throw new Exception("Unable to get user from Domain or Machine context.");
return up;
}
protected void GetYear()
{
DTO objc = new DTO();
{
DrpForYear.DataSource = obj.GetYear();
DrpForYear.DataTextField = "Year";
DrpForYear.DataBind();
}
}
protected void GetMonth()
{
DTO objc = new DTO();
{
DrpForMonth.DataSource = obj.GetMonth(); ;
DrpForMonth.DataTextField = "Month";
DrpForMonth.DataBind();
}
}
public void GrdGetComments()
{
DTO objc = new DTO();
{
objc.LogdInUsername = Convert.ToString(Session["LogdInUsername"]);
DataSet GrdVC = obj.GetButtonComment(objc);
DataView GrdViewC = new DataView();
GrdViewC.Table = GrdVC.Tables[0];
gvData.DataSource = GrdViewC;
gvData.DataBind();
}
}
protected void BtnSave_Click(object sender, EventArgs e)
{
DTO objc = new DTO();
int Flag = 0;
LblLogdInUsername.Text = Session["Username"].ToString();
objc.LogdInUsername = LblLogdInUsername.Text;
objc.DateTime = DateTime.Now;
objc.Comments = TxtComments.Text;
objc.Company = LblCompany.Text;
LblName.Text = Session["Name"].ToString();
objc.Name = LblName.Text;
objc.Year = DrpForYear.SelectedItem.Text;
objc.Month = DrpForMonth.SelectedItem.Text;
objc.ViewPreference = RadView.SelectedItem.Text;
int X = obj.InsertButtonComment(objc);
if (X >= 0)
{
Flag = 1;
}
else
{
Flag = 0;
}
if (Flag == 1)
{
LblSuccess.Visible = true;
LblSuccess.Text = "Comment Saved";
}
else
{
LblErr.Visible = true;
LblErr.Text = "Failed To Save Comment!!!";
}
objc.LogdInUsername = Convert.ToString(Session["LogdInUsername"]);
DataSet GrdVC = obj.GetButtonComment(objc);
DataView GrdViewC = new DataView();
GrdViewC.Table = GrdVC.Tables[0];
gvData.DataSource = GrdViewC;
gvData.DataBind();
TxtComments.Text = "";
DrpForYear.ClearSelection();
DrpForMonth.ClearSelection();
RadView.Text = "";
}
protected void gvData_RowEditing(object sender, GridViewEditEventArgs e)
{
gvData.EditIndex = e.NewEditIndex;
GrdGetComments();
}
protected void gvData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvData.EditIndex = -1;
GrdGetComments();
}
protected void gvData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DTO objc = new DTO();
Label lblBtnID = (Label)gvData.Rows[e.RowIndex].FindControl("lblBtnID");
Label lblLogdInUsername = (Label)gvData.Rows[e.RowIndex].FindControl("lblLogdInUsername");
Label lblYear = (Label)gvData.Rows[e.RowIndex].FindControl("lblYear");
Label lblMonth = (Label)gvData.Rows[e.RowIndex].FindControl("lblMonth");
Label lblComments = (Label)gvData.Rows[e.RowIndex].FindControl("lblComments");
TextBox txtComments = (TextBox)gvData.Rows[e.RowIndex].FindControl("TxtComments");
LblLogdInUsername.Text = Session["Username"].ToString();
objc.LogdInUsername = LblLogdInUsername.Text;
objc.Comments = TxtComments.Text;
objc.BtnID = Convert.ToInt32(Session["BtnID"]);
int Flag = 0;
int X = obj.UpdategvData(objc);
{
if (X >= 0)
{
Flag = 1;
}
else
{
Flag = 0;
}
}
if (Flag == 1)
{
LblSuccss.Visible = true;
LblSuccss.Text = "Comment Updated";
}
else
{
LblErrr.Visible = true;
LblErrr.Text = "Failed To Update Comment!!!";
}
}
public int UpdategvData(InLogDTO b)
{
DBAccess db = new DBAccess();
SqlParameter objParam = new SqlParameter("#LogdInUsername", b.LogdInUsername);
objParam.Direction = ParameterDirection.Input;
objParam.Size = 50;
db.Parameters.Add(new SqlParameter("#Comments", b.Comments));
db.Parameters.Add(new SqlParameter("#BtnID", b.BtnID));
db.Parameters.Add(objParam);
int retval = db.ExecuteNonQuery("UpdategvData");
if (retval >= 1)
{
int i = 0;
return i;
}
else
{
return -1;
}
}
stored procedure
ALTER PROCEDURE [dbo].[UpdategvData]
#LogdInUsername nvarchar(50) ,
#Comments nvarchar(50),
#BtnID int
AS
Update dbo.Button_Comments
Set Comments = #Comments
Where LogdInUsername = #LogdInUsername and ViewPreference = 'Public' and
Comments = #Comments and BtnID = #BtnID;

GrdGetComments(); is running in your Page_Load, which binds the gridview again after editing (without saving). This needs to be in the (!IsPostBack).
Page life cycle indicates that Page_Load will always run before any other button clicks:
http://msdn.microsoft.com/en-us/library/ms178472(v=vs.90).aspx
You need to bind your gridview inside the if (!IsPostBack).
The stored procedure also needs a return value, for example adding a return to the end will allow you to grab this within your C# code.

Related

How can I update a specific column in my gridview after a timed event?

In my web app I have a GridView that gets information from the SQL database then I have a timed event that pings the IP addresses every 5 seconds. If the response is less that 15ms the icon is displayed as a green tick. If more that 15ms the icon changes to a yellow exclamation mark, and when timed out a red error icon.
The code is working like it should(regarding the timed event), however the icon doesn't get replaced according to the timed response instead it adds a new icon every time
for example:
if the time is less that 15ms on first timed event:
Y
if the time is more than 15 ms on second timed event:
Y !
As you can see the Y remains whereas it should then just display the !
This is my code (aspx)
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:constr %>"
SelectCommand="SELECT ip, host, device FROM [servers]"></asp:SqlDataSource>
<asp:Timer runat="server" ID="UpdateTimer" Interval="5000" OnTick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" id="TimedPanel" updatemode="Conditional">
<triggers>
<asp:AsyncPostBackTrigger controlid="UpdateTimer" eventname="Tick" />
</triggers>
<ContentTemplate>
<asp:GridView ID="GridView1" CssClass="gridview" runat="server" AllowSorting="True"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1" DataKeyNames="ip" Width="100%">
<AlternatingRowStyle CssClass="AltRow"></AlternatingRowStyle>
<Columns>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Image ID="Image3" runat="server" Visible="False" ImageUrl="~/Images/green.png" />
<asp:Image ID="Image4" runat="server" Visible="False" ImageUrl="~/Images/red.png" />
<asp:Image ID="Image5" runat="server" Visible="False" ImageUrl="~/Images/yellow.png" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="ip" HeaderText="IP Address" />
<asp:BoundField DataField="host" HeaderText="Host Name" />
<asp:BoundField DataField="device" HeaderText="Description" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
For the code behind:
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
Servers();
}
private void Servers()
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Image Image3 = (Image)row.FindControl("Image3");
Image Image4 = (Image)row.FindControl("Image4");
Image Image5 = (Image)row.FindControl("Image5");
TimedPanel.Update();
string destIP = GridView1.DataKeys[row.RowIndex].Value.ToString();
{
try
{
Ping p = new Ping();
PingReply reply;
reply = p.Send(destIP);
if (reply.Status == IPStatus.Success)
{
if (reply.RoundtripTime > 15)
{
Image5.Visible = true;
Image5.ToolTip = Convert.ToString("RoundTripTime: " + reply.RoundtripTime + "ms");
}
else
Image3.Visible = true;
Image3.ToolTip = Convert.ToString("RoundTripTime: " + reply.RoundtripTime + "ms");
}
else
{
Image4.Visible = true;
Image4.ToolTip = reply.Status.ToString();
}
}
catch (PingException err)
{
Image4.ToolTip = err.Message.ToString();
Image4.Visible = true;
}
}
}
}
}
What I have tried was to update the panel by using:
TimedPanel.Update();
This didn't work though. Obviously when I refresh the entire page then it works but don't want to do that. I am also not sure if one can update just the column where the icons are being displayed after each timed event.
Any suggestions on how I get the icons to display one at a time after the timed event?
Thanks
Okay, I have resolved the issue.
Remove the Images from the ItemTemplate and add a panel
<ItemTemplate>
<asp:Panel runat="server" ID="Panel4"></asp:Panel>
</ItemTemplate>
Change the code behind to
Image Image2 = new Image();
Image Image3 = new Image();
Image Image4 = new Image();
Panel serverPanel = (Panel)row.FindControl("Panel4");
Add the images like this:
if (reply.Status == IPStatus.Success)
{
if (reply.RoundtripTime > 50)
{
Image2.ImageUrl = "../Images/yellow.png";
serverPanel.Controls.Add(Image2);
Image2.ToolTip = Convert.ToString("RoundTripTime: " + reply.RoundtripTime + "ms");
}
else
{
Image3.ImageUrl = "../Images/green.png";
serverPanel.Controls.Add(Image3);
Image3.ToolTip = Convert.ToString("RoundTripTime: " + reply.RoundtripTime + "ms");
}
}
else
{
Image4.ImageUrl = "../Images/red.png";
serverPanel.Controls.Add(Image4);
Image4.ToolTip = reply.Status.ToString();
}
}
catch (PingException err)
{
Image4.ImageUrl = "../Images/red.png";
serverPanel.Controls.Add(Image4);
Image4.ToolTip = err.Message.ToString();
}
so it will then be:
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
ConnectionString="<%$ ConnectionStrings:constr %>"
SelectCommand="SELECT ip, host, device FROM [addfirewall]"></asp:SqlDataSource>
<asp:Timer runat="server" ID="UpdateTimer3" Interval="5000" OnTick="UpdateTimer3_Tick" />
<asp:UpdatePanel runat="server" ID="UpdatePanel3" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView4" CssClass="gridview" runat="server" AllowSorting="True"
AutoGenerateColumns="False" DataSourceID="SqlDataSource4" DataKeyNames="ip" Width="100%">
<AlternatingRowStyle CssClass="AltRow"></AlternatingRowStyle>
<Columns>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Panel runat="server" ID="Panel4"></asp:Panel>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="ip" HeaderText="IP Address" />
<asp:BoundField DataField="host" HeaderText="Host Name" />
<asp:BoundField DataField="device" HeaderText="Description" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateTimer3" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
Code Behind:
private void Servers()
{
foreach (GridViewRow row in GridView4.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Image Image2 = new Image();
Image Image3 = new Image();
Image Image4 = new Image();
Panel serverPanel = (Panel)row.FindControl("Panel4");
string destIP = GridView4.DataKeys[row.RowIndex].Value.ToString();
{
try
{
Ping p = new Ping();
PingReply reply;
reply = p.Send(destIP);
if (reply.Status == IPStatus.Success)
{
if (reply.RoundtripTime > 50)
{
Image2.ImageUrl = "../Images/yellow.png";
serverPanel.Controls.Add(Image2);
Image2.ToolTip = Convert.ToString("RoundTripTime: " + reply.RoundtripTime + "ms");
}
else
{
Image3.ImageUrl = "../Images/green.png";
serverPanel.Controls.Add(Image3);
Image3.ToolTip = Convert.ToString("RoundTripTime: " + reply.RoundtripTime + "ms");
}
}
else
{
Image4.ImageUrl = "../Images/red.png";
serverPanel.Controls.Add(Image4);
Image4.ToolTip = reply.Status.ToString();
}
}
catch (PingException err)
{
Image4.ImageUrl = "../Images/red.png";
serverPanel.Controls.Add(Image4);
Image4.ToolTip = err.Message.ToString();
}
}
}
}
}

I am trying to export grid data into CSV but Audiofilename column data is not displaying

I am trying to export Grid data to csv file in asp.net i exported successfully but Audio File name column data is not displaying in downloaded file (it is button in TemplateField tag i need to print button text in csv file ) ,anything i forget to add ? How to fix this issue ? Thank you
.aspx code
<asp:GridView ID="GridView1" Font-Size="Medium" CssClass="mGrid" runat="server"
HeaderStyle-CssClass="header-center" PageSize="15"
AutoGenerateColumns="false" AllowPaging="True" AllowSorting="True"
OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<%--<asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-ForeColor="White" />--%>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#Eval("Id")%>' CommandArgument='<%#Eval("Id")%>' Visible="false">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Vendor Name" />
<asp:BoundField DataField="AudFileSize" HeaderText="AudFileSize" />
<asp:BoundField DataField="AudFileDuration" HeaderText="AudFileDuration" />
<%-- <asp:TemplateField HeaderText="Audio FileName">
<ItemTemplate>
<asp:Button ID="btnAudioFileName"
Text='<%#System.IO.Path.GetFileNameWithoutExtension(Eval("AudioFileName").ToString())%>'
runat="server" CommandArgument='<%#Eval("AudioFileName")%>'
class="btn btn-link" CommandName="AudioFileName" />
<%-- <sup><asp:Label ID ="lblrepetedCount" Text='<%#Eval("Reject")%>' runat="server"
CommandArgument='<%#Eval("Reject")%>' CommandName="Reject"></asp:Label></sup>--%>
<%-- </ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Audio FileName">
<ItemTemplate>
<asp:Button ID="btnAudioFileName"
Text='<%#System.IO.Path.GetFileNameWithoutExtension(Eval("AudioFileName").ToString())%>'
runat="server" CommandArgument='<%#Eval("AudioFileName")%>'
class="btn btn-link" CommandName="AudioFileName" />
<%-- <sup><asp:Label ID ="lblrepetedCount" Text='<%#Eval("Reject")%>' runat="server"
CommandArgument='<%#Eval("Reject")%>' CommandName="Reject"></asp:Label></sup>--%>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="FirstName" HeaderText="Physician Name" />--%>
<%--<asp:BoundField DataField="PhysicianID" HeaderText="PhysicianID" />--%>
<asp:BoundField DataField="MrnNo" HeaderText="MrnNo" NullDisplayText=" " />
<asp:BoundField DataField="PatientName" HeaderText="PatientName" NullDisplayText=" "/>
<asp:BoundField DataField="PhysicianName" HeaderText="PhysicianName" />
<asp:BoundField DataField="Reject" HeaderText="Reject" Visible="false" />
<%--<asp:BoundField DataField="BucketName" HeaderText="Bucket Name" Visible="false" />--%>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lblBucketName" runat="server" Text='<%#Eval("BucketName")%>' CommandArgument='<%#Eval("BucketName")%>' Visible="false">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs code here
protected void btnExportToCSV_Click(object sender, EventArgs e)
{
ExportGridToCSV();
}
private void ExportGridToCSV()
{
//To Export all pages
GridView1.AllowPaging = false;
FillData();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Transcribeworkdetails.csv");
Response.Charset = "";
Response.ContentType = "application/text";
GridView1.AllowPaging = false;
GridView1.DataBind();
string[] hiddenCols = { "", "Reject" };
StringBuilder columnbind = new StringBuilder();
for (int k = 0; k < GridView1.Columns.Count; k++)
{
bool isHidden = true;
foreach (string str in hiddenCols)
{
if (GridView1.Columns[k].HeaderText == str)
{
isHidden = false;
break;
}
}
if (isHidden)
columnbind.Append(GridView1.Columns[k].HeaderText + ',');
}
columnbind.Append("\r\n");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int k = 0; k < GridView1.Columns.Count; k++)
{
bool isHidden = true;
foreach (string str in hiddenCols)
{
if (GridView1.Columns[k].HeaderText == str)
{
isHidden = false;
break;
}
}
if (isHidden)
{
columnbind.Append(GridView1.Rows[i].Cells[k].Text + ',');
}
}
columnbind.Append("\r\n");
}
Response.Output.Write(columnbind.ToString());
Response.Flush();
Response.End();
}

DropdownList with Checkbox in a GridView

Here is my current grid view.
<asp:GridView ID="grdIndexGroupMap" runat="server" AutoGenerateColumns="False" DataKeyNames="IndexName"
OnRowCancelingEdit="grdIndexGroupMap_RowCancelingEdit" OnRowDataBound="grdIndexGroupMap_RowDataBound"
OnRowEditing="grdIndexGroupMap_RowEditing" OnRowUpdating="grdIndexGroupMap_RowUpdating"
OnRowCommand="grdIndexGroupMap_RowCommand" ShowFooter="True" OnRowDeleting="grdIndexGroupMap_RowDeleting"
CellPadding="1" CellSpacing="1" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<%--IndexName--%>
<asp:TemplateField HeaderText="IndexName" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:DropDownList ID="cmbIndexName" runat="server" DataTextField="LocationName" DataValueField="IndexId"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblIndexName" runat="server" Text='<%# Eval("IndexName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="cmbNewIndexName" runat="server" DataTextField="IndexName" DataValueField="IndexId"></asp:DropDownList>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
How do replace the DropDownList with a dropdown where I can select multiple items?
A checkboxlist in dropdownlist or a listbox with multiselect in dropdown. When selected will show comma seperated values.
Tried a couple of ways but wont work.
here is my databound method:
protected void grdIndexGroupMap_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList cmbIndexName = (DropDownList)e.Row.FindControl("cmbIndexName");
if (cmbIndexName != null)
{
cmbIndexName.DataSource = _Indexes;
cmbIndexName.DataTextField = "IndexName";
cmbIndexName.DataValueField = "IndexId";
cmbIndexName.DataBind();
cmbIndexName.SelectedValue = grdIndexGroupMap.DataKeys[e.Row.RowIndex].Values[1].ToString();
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList cmbNewIndexName = (DropDownList)e.Row.FindControl("cmbNewIndexName");
cmbNewIndexName.DataSource = _Indexes;
cmbNewIndexName.DataBind();
}
}
I am using ASP.Net, C#
How about:
<asp:TemplateField HeaderText="IndexName" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:PlaceHolder id="phListContainer" runat="server" />
</EditItemTemplate>
then in your code-behind:
if (e.Row.RowType == DataControlRowType.DataRow)
{
phListContainer = (PlaceHolder)e.Row.FindControl(phListContainer);
if (phListContainer != null)
{
//Adding a DropDownList
var cmbIndexName = new DropDownList();
cmbIndexName.DataSource = _Indexes;
cmbIndexName.DataTextField = "IndexName";
cmbIndexName.DataValueField = "IndexId";
cmbIndexName.DataBind();
cmbIndexName.SelectedValue = grdIndexGroupMap.DataKeys[e.Row.RowIndex].Values[1].ToString();
phListContainer.Controls.Add(cmbIndexName);
// OR
//Adding a CheckBoxList;
cmbIndexName = new CheckBoxList();
cmbIndexName.DataSource = _Indexes;
cmbIndexName.DataTextField = "IndexName";
cmbIndexName.DataValueField = "IndexId";
cmbIndexName.DataBind();
phListContainer.Controls.Add(cmbIndexName);
}
}
Then you can get the controls by
var cbList = (CheckBoxList)e.Row.FindControl(phListContainer).Controls[0];
and then you can loop through and find the checked boxes
for(int i = 0; i < cbList.Items.Count; ++i)
{
if(cbList.Items[i].Selected)
//Do stuff
}

Gridview becomes out of shape when rebinds

I have binded gridview to database and it loads on TICKER's event. It works good but problem is that when it rebinds then GIRDVIEW's layout and shape becomes improper and disturbed, kinda messed up.
<asp:GridView ID="GridViewSmsComplaints" AllowPaging="True" PageSize="4" runat="server" AutoGenerateColumns="False" CssClass="mGrid" BorderColor="#333333" Width="550px" OnRowDataBound="GridViewSmsComplaints_RowDataBound" OnPageIndexChanging="GridViewSmsComplaints_PageIndexChanging" >
<Columns>
<asp:BoundField HeaderText="ID" DataField="ID" />
<asp:BoundField HeaderText="Recieving Date" DataField="RecievingDate" />
<%--<asp:BoundField HeaderText="ToMobileNo" DataField="ToMobileNo" /> --%>
<asp:BoundField HeaderText="FromMobileNo" DataField="FromMobileNo" />
<asp:BoundField HeaderText="Message" DataField="Message" >
<ItemStyle Wrap="True" />
</asp:BoundField>
<asp:TemplateField HeaderText="IsComplaint">
<ItemTemplate>
<asp:CheckBox ID="ckboxIsComplaint" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Timer runat="server" Interval="20000" ID="RefreshSmsComplaints" OnTick="RefreshSmsComplaints_Tick" />
</ContentTemplate>
</asp:UpdatePanel>
Ticker:
protected void RefreshSmsComplaints_Tick(object sender, EventArgs e)
{
// ReportViewer1.Visible = false;
foreach (GridViewRow row in GridViewSmsComplaints.Rows)
{
CheckBox checkbox = (CheckBox)row.FindControl("ckboxIsComplaint");
if (checkbox.Checked == true)
{
CheckedRows.Add(row.RowIndex);
}
else
{
CheckedRows.Remove(row.RowIndex);
}
}
try
{
DateTime fromDate = DateTime.ParseExact(txtFromDate.Text, "dd/MMM/yyyy", null);
DateTime toDate = DateTime.ParseExact(txtToDate.Text, "dd/MMM/yyyy", null);
DataTable dt = ManageRecievedMessage.GetSmsComplaintsByDate(fromDate, toDate);
//GridViewSmsComplaints.Attributes.Add("style", "word-break:keep-all;word-wrap:normal");
if (dt.Rows.Count > 0)
{
GridViewSmsComplaints.DataSource = dt;
GridViewSmsComplaints.DataBind();
GridViewSmsComplaints.Visible = true;
//gridViewComplaintsBySubject.Visible = false;
}
else
{
dt.Rows.Add(dt.NewRow());
GridViewSmsComplaints.DataSource = dt;
GridViewSmsComplaints.DataBind();
int totalcolums = GridViewSmsComplaints.Rows[0].Cells.Count;
GridViewSmsComplaints.Rows[0].Cells.Clear();
GridViewSmsComplaints.Rows[0].Cells.Add(new TableCell());
GridViewSmsComplaints.Rows[0].Cells[0].ColumnSpan = totalcolums;
GridViewSmsComplaints.Rows[0].Cells[0].Text = "No Data Found for this date combination";
GridViewSmsComplaints.Visible = true;
//gridViewComplaintsBySubject.Visible = false;
}
}
catch
{
HiddenFieldSetMessage.Value = "SomethingWrong";
HiddenFieldShowMessage.Value = "True";
}
}

how to do custom paging with paging template in asp gridview?

so let say i want to create paging like "> 1 2 3 4 5 6 <" and i decided to use paging template in gridview and this is what i do :
aspx file :
<asp:GridView ID="gvDept" runat="server" CellPadding="4" ForeColor="Black"
GridLines="Horizontal" AutoGenerateColumns="False" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
AllowSorting="True" AllowPaging="True" AllowCustomPaging="True"
DataSourceID="DS" DataKeyNames="departementcode" PageSize="3" OnRowCommand="gvDept_RowCommand">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox runat="server" ID="cbSelectAll" onclick="SelectAll(this)"></asp:CheckBox>
<%-- <asp:CheckBox runat="server" ID="cbAll" OnCheckedChanged="cbAll_CheckedChanged" AutoPostBack="true"></asp:CheckBox>--%>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="cbSelectOne"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:HyperLinkField text="Edit" DataNavigateUrlFields="departementcode"
DataNavigateUrlFormatString="ManageDepartement.aspx?flag=edit&departementcode={0}" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete"
OnClientClick="return confirm ('Are you sure?');" Text="Delete">
</asp:LinkButton>
</ItemTemplate>
<ItemStyle ForeColor="Red" />
</asp:TemplateField>
<asp:BoundField DataField="departementcode" HeaderText="Departement Code" ReadOnly="True" SortExpression="departementcode" />
<asp:BoundField DataField="departementname" HeaderText="Departement Name" SortExpression="departementname" />
<asp:BoundField DataField="createby" HeaderText="Create By" SortExpression="createby" />
<asp:BoundField DataField="createdate" HeaderText="Create Date" SortExpression="createdate" />
<asp:BoundField DataField="updateby" HeaderText="Update By" SortExpression="updateby" />
<asp:BoundField DataField="lastupdate" HeaderText="Last Update" SortExpression="lastupdate" />
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black"/>
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerSettings Mode="Numeric" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Center" CssClass="paging"/>
<PagerTemplate>
</PagerTemplate>
<RowStyle BorderColor="White"/>
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>
<asp:LinqDataSource ID="DS" runat="server" ContextTypeName="Admin.AirAsiaDCDataContext"
EntityTypeName="" TableName="departements" EnableDelete="True" OnDeleted="DS_Deleted">
</asp:LinqDataSource>
and then i also put this code in C# :
protected void Page_Load(object sender, EventArgs e)
{
AirAsiaDCDataContext dc = new AirAsiaDCDataContext();
int dtcount = dc.departements.Count();
int pgcount = 0;
if (dtcount % 3 > 0)
{
pgcount = (dtcount / 3) + 1;
}
else
{
pgcount = pgcount / 3;
}
Button pagerBTN;
for (int i = 1; i <= pgcount; i++)
{
if(i == 1)
{
pagerBTN = new Button();
pagerBTN.ID = "btNext";
pagerBTN.Text = ">";
pagerBTN.CommandName = "Next";
gvDept.BottomPagerRow.Cells[0].Controls.Add(pagerBTN);
}
pagerBTN = new Button();
pagerBTN.ID = "bt" + i;
pagerBTN.Text = i.ToString();
pagerBTN.CommandName = i.ToString();
gvDept.BottomPagerRow.Cells[0].Controls.Add(pagerBTN);
if (i == pgcount)
{
pagerBTN = new Button();
pagerBTN.ID = "btLast";
pagerBTN.Text = "<";
pagerBTN.CommandName = "Last";
gvDept.BottomPagerRow.Cells[0].Controls.Add(pagerBTN);
}
}
}
protected void gvDept_RowCommand(object sender, GridViewCommandEventArgs e)
{
AirAsiaDCDataContext dc = new AirAsiaDCDataContext();
int datacount = dc.departements.Count();
int pagecount = 0;
int prevIDX = 0;
if (datacount % 3 > 0)
{
pagecount = (datacount / 3) + 1;
}
else
{
pagecount = datacount / 3;
}
if (e.CommandName == "Next")
{
if (gvDept.PageIndex < pagecount - 1)
{
prevIDX = gvDept.PageIndex;
gvDept.PageIndex = gvDept.PageIndex + 1;
if (prevIDX == pagecount - 2)
{
Button btn = (Button)gvDept.BottomPagerRow.Cells[0].FindControl("btNext");
btn.Visible = false;
}
}
}
else if (e.CommandName == "Prev")
{
if (gvDept.PageIndex > 0)
{
prevIDX = gvDept.PageIndex;
gvDept.PageIndex = gvDept.PageIndex - 1;
if (prevIDX == 1)
{
Button btn = (Button)gvDept.BottomPagerRow.Cells[0].FindControl("btPrev");
btn.Visible = false;
}
}
}
else
{
gvDept.PageIndex = Convert.ToInt32(e.CommandName) - 1;
}
}
my code working, but the problem is, if i click one of those paging button, after postback all my paging button which i generated before totally gone, i don't get it what i do wrong here? any correction?
In the grid view use
OnPageIndexChanging="gvDept_PageIndexChanging"
Add this code in .cs file to bind the data to grid view on each page index change.
protected void gvDept_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvDept.PageIndex = e.NewPageIndex;
// write here function to bind the grid to the datasource
}
Add this at the starting in Page_Load function so that the data gets bind to the grid view each time after postback.
if (!IsPostBack)
{
//function to bind the grid to data source
}

Categories

Resources