I have a gridview, which have data from a SQL database. The database conaints jobs that a group need to work with. On my last column it says if it's finished or not. If its done, it will show a dateTime for when its finished, but if its not, the database contains 0 for this cell, and need a Button, that can make it finished, when it is.
Therefor the code first retrive data from the database, then i want to use RowDataBound to check if i need to show a Button, instead of the text from database. I also need an event for this button, so i can update the database with, an dateTime when finished.
Here's the code for my gridview:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="OverviewPlannedJobs" DataKeyNames="ID"
onrowcommand="Gridview1_RowCommand" onrowdatabound="GridView1_RowDataBound"
Width="631px">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID"
InsertVisible="False" ReadOnly="True">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="week" HeaderText="Uke" SortExpression="week">
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="dayNumb" HeaderText="Dag"
SortExpression="dayNumb">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="oven" HeaderText="Ovn"
SortExpression="oven">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="section" HeaderText="Seksjon"
SortExpression="section">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="pit" HeaderText="Pit" SortExpression="pit">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="job" HeaderText="Jobb"
SortExpression="job">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="priority" HeaderText="Prioritet"
SortExpression="priority">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="timeEdited" HeaderText="Lagt til eller endret"
SortExpression="timeEdited" >
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:ButtonField ButtonType="Button" CommandName="editts" HeaderText="Valg"
Text="Rediger">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:ButtonField>
<asp:ButtonField ButtonType="Button" CommandName="delete" Text="Slett">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:ButtonField>
<asp:TemplateField HeaderText="Fullført?" SortExpression="finished">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("finished") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
then i have this rowdatabound function in code behind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Make button where finished equals zero
if (e.Row.Cells[11].Text.Equals("0"))
{
//insert button
}
}
I'm sorry, its not working for me. Can't figure out why, but get error at one of these
DataRow row = ((DataRowView)e.Row.DataItem).Row;
string value0 = row[3].ToString();
i don't have an own databinding method since i've used the configure datasource for the gridview.
Think i will try to make an button itemtemplate, and then change the text, or disable button depending on the database result.
Try this i have tested
Code Behind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow row = ((DataRowView)e.Row.DataItem).Row;
string value0 = row[3].ToString();
if (value0 == "0")
{
e.Row.Cells[2].Text = "";
Button btn=new Button();
btn.Text="finish";
e.Row.Cells[2].Controls.Add(btn);
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
gvBind();
}
public void gvBind()
{
SqlDataAdapter dap=new SqlDataAdapter("select id,name,job,status from myTable",con);
DataSet ds = new System.Data.DataSet();
dap.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
Defautl.aspx:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate >
<asp:Label ID="l1" Text='<%# Bind("name") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Job">
<ItemTemplate >
<asp:Label id="l2" Text='<%# Bind("job") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate >
<asp:Label ID="l3" Text='<%# Bind("status") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
ScreenShot:
Mark answer if it help :)
Related
I want to show Checkbox in Gridview,
But now, it only show dynamic data in Gridview,
Didn't show dynamic checkbox in Gridview.
How can I fix problem, thanks.
.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
using (var conn = new SqlConnection(strConn))
{
try
{
conn.Open();
ckloginConnectionString.SelectCommand = #"select a,b,c,d ,e from testTable where a =#a ";
ckloginConnectionString.SelectParameters.Add("a", a);
//==================
DataView dv = (DataView)ckloginConnectionString.Select(new DataSourceSelectArguments());
GridView1.DataSource = dv;
GridView1.DataBind();
//==================
ckloginConnectionString.DataBind();
ckloginConnectionString.DataBind();
}
catch (Exception ex)
{
ex.ToString();
}
}
}
.aspx
<div class="table-wrapper">
<asp:GridView runat="server" ID="GridView1" CssClass="alt" DataKeyNames="InsertedDate,Upload_Schoo_No" AutoGenerateColumns="False" OnRowCommand="grvclscour_RowCommand">
<Columns>
<asp:TemplateField HeaderText="check" InsertVisible="false" ItemStyle-BorderStyle="Double">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Visible="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="a" HeaderText="a">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="b" HeaderText="b">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="c" HeaderText="c">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:ButtonField CommandName="d" HeaderText="d">
<ItemStyle HorizontalAlign="Center" />
</asp:ButtonField>
<asp:ButtonField CommandName="e" HeaderText="e">
<ItemStyle HorizontalAlign="Center" />
</asp:ButtonField>
</Columns>
</asp:GridView>
</div>
Eval would do what you want i guess.
change your grid desing like this:
<asp:GridView runat="server" ID="GridView1" CssClass="alt" DataKeyNames="InsertedDate,Upload_Schoo_No" AutoGenerateColumns="False" OnRowCommand="grvclscour_RowCommand">
<Columns>
<asp:TemplateField HeaderText="check" InsertVisible="false" ItemStyle-BorderStyle="Double">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Visible="true" Checked='<%# Eval("YourDataField") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="a" HeaderText="a">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="b" HeaderText="b">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="c" HeaderText="c">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:ButtonField CommandName="d" HeaderText="d">
<ItemStyle HorizontalAlign="Center" />
</asp:ButtonField>
<asp:ButtonField CommandName="e" HeaderText="e">
<ItemStyle HorizontalAlign="Center" />
</asp:ButtonField>
</Columns>
</asp:GridView>
please help with this hyperlink thing.. i got a grid view where one of the column contains hyperlink say ViewDetails. upon clicking ViewDetails it should get navigate to another page called as Reports.aspx where the page should display the grid row value of selectd column in grid view in labels. i have used row data bound event .. im getting blank labels if i click the hyperlink . i have written stored procedure to get the row values. and im calling it through KEY.. its TaskID which is an auto generated column which is invisible. depending on the key value i need to display the row values.
here are the codes
<asp:GridView ID="GrdViewMyTasks" runat="server" AllowSorting="True"
AutoGenerateColumns="False" BackColor="White" BorderColor="#0061C1"
BorderStyle="None" CaptionAlign="Bottom" EmptyDataText="No Records Found"
Font-Names="Verdana" Font-Size="X-Small" ForeColor="#0061C1"
Height="179px" OnRowDataBound="GrdViewMyTasks_RowDataBound"
ShowFooter="True" ShowHeaderWhenEmpty="True" Width="99%"
onselectedindexchanged="GrdViewMyTasks_SelectedIndexChanged"
OnRowCreated="GrdViewMyTasks_RowCreated" >
<Columns>
<asp:BoundField DataField="TaskID" HeaderText="SL No" Visible="False" ReadOnly="True">
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:TemplateField HeaderText="Task Name">
<ItemTemplate>
<asp:Label ID="TaskName" runat="server"
Font-Names="Verdana" Font-Size="X-Small" Height="24px"
Text='<%# Eval("TaskName")%>' Width="70px"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Due Date">
<ItemTemplate>
<asp:Label ID="DueDate" runat="server" Font-Names="Verdana" Font-Size="X-Small"
Height="20px" Width="70px" Text='<%# Eval("DueDate","{0:dd/MM/yyyy}")%>' DataFormatString="{0:dd/MM/yyyy}"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="Description" runat="server" Font-Names="Verdana" Font-Size="X-Small" Height="20px" Width="90px" Text='<%# Eval("Description")%>'></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Assign By">
<ItemTemplate>
<asp:Label ID="AssignBy" runat="server" Font-Names="Verdana" Font-Size="X-Small" Height="20px" Width="90px" Text='<%# Eval("AssignBy")%>'></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="Status" runat="server" Font-Names="Verdana" Font-Size="X-Small" Height="20px" Width="90px" Text='<%# Eval("Status")%>'></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="% Complete">
<ItemTemplate>
<asp:Label ID="PercentageComplete" runat="server" Font-Names="Verdana" Font-Size="X-Small" Height="20px" Width="50px" Text='<%# Eval("PercentageComplete")%>'></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="View Details">
<ItemTemplate>
<asp:HyperLink ID="ViewDetails" runat="server" Font-Names="Verdana" Font-Size="X-Small" Height="24px" Width="70px" ForeColor="#0061C1" Text="ViewDetails" NavigateUrl="Reports.aspx">View</asp:HyperLink>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
</Columns>
</asp:GridView>
aspx.cs code
protected void GrdViewMyTasks_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink ViewDetails = e.Row.FindControl("ViewDetails") as HyperLink;
ViewDetails.NavigateUrl = "Reports.aspx?TaskID=" + e.Row.Cells[0].Text;
}
}
code in reports.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
MTMSService obj = new MTMSService();
DBAccess db = new DBAccess();
{
MTMSDTO objc = new MTMSDTO();
{
//objc.TaskID = Convert.ToInt32(Request.QueryString["TaskID"]);//
DataSet rep = obj.GetReports();
DataView Rprts = new DataView();
Rprts.Table = rep.Tables[0];
var table = rep.Tables[0];
if (table.Rows.Count > 0)
{
LblTaskID.Text = rep.Tables[0].Rows[0]["TaskID"].ToString();
LblTaskName.Text = rep.Tables[0].Rows[0]["TaskName"].ToString();
LblDueDate.Text = rep.Tables[0].Rows[0]["DueDate"].ToString();
LblDescription.Text = rep.Tables[0].Rows[0]["Description"].ToString();
LblAssignBy.Text = rep.Tables[0].Rows[0]["AssignBy"].ToString();
LblStatus.Text = rep.Tables[0].Rows[0]["Status"].ToString();
LblPercentageComplete.Text = rep.Tables[0].Rows[0]["PercentageComplete"].ToString();
}
else
{
}
LblTaskName.Visible = true;
LblAssignBy.Visible = true;
LblDescription.Visible = true;
LblDueDate.Visible = true;
LblStatus.Visible = true;
LblPercentageComplete.Visible = true;
LblAssignTo.Visible = false;
}
}
}
and this is my stored procedure
ALTER PROCEDURE [dbo].[GetReports]
#TaskID int
AS
Select TaskName, DueDate, Description, AssignBy, Status, PercentageComplete, TaskID
From dbo.Task
Where TaskID = #TaskID;
please let me know where im goin wrong. im unable to get the perfect solution for this from past 1 week... its getting headache thing ..
getting error "input string is not in correct format" at commented line of reports.cs file
You're querying the database with Session["TaskId"] and you're showing task id on UI from query string. Are you sure that both are same?
I think you might want to use taks id from query string rather than session.
objc.TaskID = Convert.ToInt32(Request.QueryString["TaskID"]);
Update -
Filter the table based on your query string
rep.Tables[0].Select(string.Format("TaskID={0}", Request.QueryString["TaskID"]));
i have a gridview that I need to have paged. When I allowPaging=true, It shows 145678910.... It won't show pages 2 and 3. If I try to change the Mode to NextPreviousFirstLast, It only shows 'Next' on the first page, and if I click that, it only shows 'First' and 'Last' on the second page. Here is the code:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="Black" AutoGenerateColumns="False" BackColor="#CCCCCC"
BorderColor="#666666" OnRowDataBound = "HandleRowDataBound" BorderStyle="Solid" BorderWidth="1px" CellSpacing="2" Width ="942px"
Font-Names="Arial" Font-Size="8pt" ShowHeaderWhenEmpty="True" CSSClass="mytable" AllowPaging="true" OnPageIndexChanging="GridView1_PageIndexChanging"
PageSize="25">
<PagerSettings Mode="NextPreviousFirstLast" FirstPageText="First" PreviousPageText="Previous" NextPageText="Next" LastPageText="Last" />
<Columns>
<asp:TemplateField HeaderText="Select" ControlStyle-Width = "30px">
<ItemTemplate>
<asp:CheckBox runat="server" ID="DiscontinuedCheckBox" CssClass="SelectCheckBox" />
</ItemTemplate>
<ControlStyle Width="30px"></ControlStyle>
<ItemStyle Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Recall Qty" ItemStyle-Wrap="true" ItemStyle-Width="100px" >
<ItemTemplate >
<img id="star1" runat ="server" src="../Images/red_star.gif" alt="Red Star" class="RedStars"/>
<asp:TextBox runat ="server" ID="textBoxQty" Width = "50px" Text ="1" ReadOnly="false" />
</ItemTemplate>
<HeaderStyle Width = "100px" />
<ItemStyle Width="100px" />
<ItemStyle Wrap="False" Width="60px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delivery Location" >
<ItemTemplate >
<div style="width:200px">
<div style ="float : left; ">
<asp:CheckBox runat="server" ID="packShipCB" Text ="Pack Ship or " CssClass="SendToShip" AutoPostBack="false" />
</div>
<asp:TextBox runat ="server" ID="deliveryLocationTB" CssClass="AllDelivery" ReadOnly ="false" Width="80px" />
</div>
</ItemTemplate>
<HeaderStyle Width = "200px" />
<ItemStyle Width="200px" />
<ItemStyle Width ="160px" />
</asp:TemplateField>
<%-- <asp:BoundField HeaderText="Data" />--%>
<asp:BoundField HeaderText="Request Number" DataField="requestNumber" ItemStyle-Width = "50px">
<HeaderStyle Wrap="True" Width="50px" />
<ItemStyle Wrap="True" Width="50px" />
</asp:BoundField>
<asp:BoundField HeaderText="Item Number" DataField="materialLineItemID" />
<asp:BoundField HeaderText="Program" DataField="programName" >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField HeaderText="Program POC" DataField="programPOC" >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField HeaderText="Material Number" DataField="materialNumber" ItemStyle-Width="100px">
<HeaderStyle Wrap="False" />
</asp:BoundField >
<asp:BoundField HeaderText="Qty in Storage" DataField="availableQty" ItemStyle-Width="100px">
<ItemStyle Width="100px" Wrap="False"></ItemStyle>
</asp:BoundField >
<asp:BoundField HeaderText="Description" DataField="Description" ItemStyle-Width="300px" >
<ItemStyle Width="300px" Wrap="False"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Serialized" DataField="Serialized" ItemStyle-Width="100px">
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Serial Number" DataField="serialNumber" ItemStyle-Width="200px">
<ItemStyle Width="200px" Wrap="False"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Shelf Life" DataField="shelfLIfe" DataFormatString="{0:d}" HtmlEncode="false" ItemStyle-Width="100px" >
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Cost Center" DataField="costCenter" ItemStyle-Width="200px">
<ItemStyle Width="200px" Wrap="False"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Charge Number" DataField="chargeNumber" ItemStyle-Width="200px">
<ItemStyle Width="200px" Wrap="False"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="contractNumber" HeaderText="Contract Number" ItemStyle-Width="200px">
<HeaderStyle Wrap="False" />
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:BoundField DataField="assetTagNumber" HeaderText="Asset Tag Number" ItemStyle-Width="200px">
<HeaderStyle Wrap="False" />
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:BoundField HeaderText="Storage Duration" DataField="Duration" ItemStyle-Width="200px">
<ItemStyle Width="200px" Wrap="False"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Handling Unit Number" DataField="handlingUnitNumber" ItemStyle-Width="100px">
<ItemStyle Width="100px" Wrap="False"></ItemStyle>
</asp:BoundField >
<asp:BoundField HeaderText="Storage Location" DataField="storageLocation" ItemStyle-Width="100px">
<ItemStyle Width="100px" Wrap="False"></ItemStyle>
</asp:BoundField >
<asp:BoundField HeaderText="Time in Storage" DataField="storageTime" ItemStyle-Width="200px">
<ItemStyle Width="200px" Wrap="False"></ItemStyle>
</asp:BoundField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="#999999" Font-Bold="True" ForeColor="#880C1B"
HorizontalAlign="Center" Font-Size="9pt" Wrap="true" BorderStyle="Solid" VerticalAlign="Middle"
BorderWidth="1px"/>
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" HorizontalAlign="Center" CssClass="Unselected"
Wrap="false" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
and here is the code behind:
protected void Page_Load(object sender, EventArgs e)
{
siteID = int.Parse(Request.QueryString["s"].ToString());
FillDetails();
}
//Pulls data from database for items to be recalled based on site, and user rights and enables to functions of the controls
private void FillDetails()
{
DataSet materials = RequestDB2.GetStoredMaterialsView(siteID);
GridView1.DataSource = materials;
GridView1.DataBind();
if (GridView1.Rows.Count >= 9)
paneling.Style["height"] = "300px";
//if not items exit
if (materials == null || materials.Tables[0].Rows.Count == 0)
{
Error.InnerText = "You have no materials to be recalled from this site.";
}
else
{
//Adds thead and tbody tags
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
protected void HandleRowDataBound(object sender, GridViewRowEventArgs e)
{
}
Here is what I see:
WHen I look at firebug, I see that pages 2 and 3 have display:none. ANy thoughts on why this might be happening?
You are not assigning data source in GridView1_PageIndexChanging. You need to assigned datasource before binding. You better try calling FillDetails()
Change
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
To
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
FillDetails();
}
Try using PagerSetting as..
<PagerSettings FirstPageText="First Page" LastPageText="Last Page"
Mode="NumericFirstLast" Position="TopAndBottom" />
protected void grdView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.DataSource = RequestDB2.GetStoredMaterialsView(siteID);
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
I want to use a dropdownlist on a gridview... I have the following code from asp.net
<asp:GridView ID="grdvEventosVendedor" runat="server" AllowPaging="True"
AutoGenerateColumns="False" CellPadding="4" DatakeyNames="idCita"
EmptyDataText="No Hay Eventos Para Este Vendedor" ForeColor="#333333"
GridLines="None" AllowSorting="True"
onpageindexchanging="grdvEventosVendedor_PageIndexChanging"
onrowcommand="grdvEventosVendedor_RowCommand"
onsorting="grdvEventosVendedor_Sorting" CellSpacing="1" HorizontalAlign="Center">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"/>
<Columns>
<asp:TemplateField HeaderText="" ItemStyle-Width="35px">
<ItemTemplate>
<asp:ImageButton ID="imgBtnEdicEvento" runat="server"
CommandArgument='<%# Eval("idCita")%>' CommandName="Edicion"
Height="32px" ImageUrl="~/img/pencil_32.png" Width="32px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="" ItemStyle-Width="35px">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDelete" runat="server"
CommandName="Borrar"
ImageUrl="~/img/1385_Disable_16x16_72.png"
onclientclick="return confirm('¿Desea eliminar el registro?');"
CommandArgument='<%# Eval("idCita")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Cliente" HeaderText="Cliente" InsertVisible="False" ReadOnly="True" SortExpression="Cliente" ItemStyle-Width="50px" />
<asp:BoundField DataField="Empresa" HeaderText="Empresa" InsertVisible="False" ReadOnly="True" SortExpression="Empresa" ItemStyle-Width="50px"/>
<asp:BoundField DataField="Telefono" HeaderText="Telefono" InsertVisible="False" ReadOnly="True" SortExpression="Telefono" ItemStyle-Width="50px"/>
<asp:BoundField DataField="Nextel" HeaderText="Nextel" InsertVisible="False" ReadOnly="True" SortExpression="Nextel" ItemStyle-Width="50px"/>
<asp:BoundField DataField="Tipo" HeaderText="Tipo" InsertVisible="False" ReadOnly="True" SortExpression="Tipo" ItemStyle-Width="50px"/>
<asp:BoundField DataField="Descripcion" HeaderText="Descripcion" InsertVisible="False" ReadOnly="True" SortExpression="Descripcion" ItemStyle-Width="100px"/>
<asp:TemplateField HeaderText="Fecha" SortExpression="Fecha" ItemStyle-Width="50px">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "Fecha", "{0:dd/MM/yyyy}")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbxFecha" runat="server" Text='<%#Bind("Fecha","{0:dd/MM/yyyy}") %>' ValidationGroup="gpEdicionAgenda">
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="HoraInicio" HeaderText="Hora" InsertVisible="False" ReadOnly="True" SortExpression="HoraInicio" ItemStyle-Width="50px"/>
<asp:BoundField DataField="Lugar" HeaderText="Lugar" InsertVisible="False" ReadOnly="True" SortExpression="Lugar" ItemStyle-Width="50px"/>
<asp:TemplateField HeaderText="Estado" ItemStyle-Width="50px">
<ItemTemplate>
<asp:DropDownList ID="dpdListEstatus" runat="server">
<asp:ListItem>Pendiente</asp:ListItem>
<asp:ListItem>Atendido</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CRM" ItemStyle-Width="25px">
<ItemTemplate>
<asp:ImageButton ID="imgBtnCRM" runat="server"
CommandArgument='<%# Eval("IdCliente")%>' CommandName="CRM"
ImageUrl="~/img/activar.png" Width="16px" Height="16px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="VM" ItemStyle-Width="25px">
<ItemTemplate>
<asp:ImageButton ID="imgBtnVerMas" runat="server"
CommandArgument='<%# Eval("IdCliente")%>' CommandName="VerMas"
ImageUrl="~/img/search.png" Width="16px" Height="16px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" Font-Size="Small" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" Font-Size="Larger" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Center" Font-Size="Small" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
The part where it says is the part where I want the ddl to be...
You'll might've also noticed that I use a total of 4 buttons for edit, delete, etc...
However I guess that's another story...
I want it to do a couple of things... first of, you'll notice that I have the dropdownlist with 2 values... that's because I get a datasource from a query, and those are the 2 possible values that this column can get...
So #1 should be... how can I make that the Ddl's Selected Value is the one I get from the query....
and #2 I can manually change the value of the ddl, so I want it to make a postback and update that specific row with the new value (the reason I need the postback would be so I can trigger for example a ddl ONSELECTEDINDEX CHANGED and therefore use the cs file to create a new query, update the row, and then refresh the gridview again)
I suppose that all of this might have something to do with rowcommand, just like the way the other 4 buttons work.
I'm using C# on this, so It would be helpful if you can help me using C# if you're method involves the cs file...
Thanks
You should use the OnRowDatabound event on the GridView. Like:
<asp:GridView ID="grdvEventosVendedor" OnRowDatabound="grdvEventosVendedor_RowDataBound">
<asp:TemplateField HeaderText="Estado" ItemStyle-Width="50px">
<ItemTemplate>
<asp:DropDownList ID="dpdListEstatus" runat="server" OnSelectedIndexChanged="dpdListEstatus_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem>Pendiente</asp:ListItem>
<asp:ListItem>Atendido</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
Then in the .cs backend code you should find the control and set it's selected value based on the dataitem values.
protected void grdvEventosVendedor_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList dpdListEstatus = e.Row.FindControl("dpdListEstatus") as DropDownList;
dpdListEstatus.SelectedValue = DataBinder.Eval(e.Row.DataItem, "FieldName").ToString();
}
}
protected void dpdListEstatus_SelectedIndexChanged(object sender, EventArgs e)
{
//your logic goes here
}
You can set the SelectedIndexChanged on your dropdown in the ASPX code and in that piece of backend code you can continue your logic.
Ow, and don't forget to set the autopostback = true on your dropdown.
You can use GridView RowDataBound event to access drop down list, similarly set selectedindexchanged event for the dropdownlist.
Refer to this link below which shows the basics of the solutions you will need
http://www.codeproject.com/Articles/53559/Accessing-a-DropDownList-inside-a-GridView
This is what I did that worked for me:
**Snippet from aspx:**
<asp:TemplateField HeaderText="RECORD_STATUS" SortExpression="RECORD_STATUS">
<EditItemTemplate>
<asp:DropDownList runat="server" ID="ddlRecStatus" SelectedIndex='<%# GetselectedRecStatus(Eval("RECORD_STATUS")) %>'
DataSource = '<%# Recs_Status %>' />
</EditItemTemplate>
</asp:TemplateField>
**Snippet from code-behind:**
protected void grdSAEdit_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Get the refernce to the list control
DropDownList ddlRecStatus = (DropDownList)(grdSAEdit.Rows[e.RowIndex].FindControl("ddlRecStatus"));
// Add it to the parameters
e.NewValues.Add("RECORD_STATUS", ddlRecStatus.Text);
}
protected string[] Recs_Status
{
get { return new string[] { "A", "E", "V", "Z" }; }
}
protected int GetselectedRecStatus(object status)
{
return Array.IndexOf(Recs_Status, status.ToString());
}
OnRowDataBound="grdViewCInfo_RowDataBound"
>
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<Columns>
<asp:TemplateField HeaderText="Concert Name" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="150px" ItemStyle-Wrap="true">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#Bind("Concert_Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#Bind("Concert_Name") %>'></asp:TextBox>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center" Height="40px"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="150px" ItemStyle-Wrap="true">
<ItemTemplate>
<asp:Label ID="lblAddr" runat="server" Text='<%#Bind("Address") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAddr" runat="server" Text='<%#Bind("Address") %>'></asp:TextBox>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center" Height="40px"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="City" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%#Bind("City") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCity" runat="server" Text='<%#Bind("City") %>'></asp:TextBox>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Pincode" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblPincode" runat="server" Text='<%#Bind("Pincode") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPincode" runat="server" Text=' <%#Bind("Pincode") %>'></asp:TextBox>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblcountry" runat="server" Text='<%#Bind("Country") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCountry" runat="server" >
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Concert Date and Time" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblDateTime" runat="server" Text='<%#Bind("Concert_Date") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDateTime" runat="server" Text='<%#Bind("Concert_Date") %>'></asp:TextBox>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" CausesValidation="False">
<ItemStyle Width="50px" />
</asp:CommandField>
<asp:CommandField ShowDeleteButton="true">
<ItemStyle Width="50px" />
</asp:CommandField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
A part of this should be done at RowDataBound also.
Here is some sample code
private static DataSet ds;
private const string query = "select * from tblcountrynames";
protected void grdViewCInfo_RowEditing(object sender, GridViewEditEventArgs e)
{
grdViewCInfo.EditIndex = e.NewEditIndex;
//guessing that this is your databind event
dbLoad();
}
protected void grdViewCInfo_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
//your ddl
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlCountry");
PopulateCountries(ddl, query);
//grdViewCInfo.Rows[e.NewEditIndex].Cells[4].Controls.Add(ddl);
}
}
private void PopulateCountries(DropDownList ddl, string query)
{
if(ds!= null && ds.Tables[0].Rows.Count >0)
MySqlConnection objMycon1 = new MySqlConnection(strProvider);
//commenting open; as adapter doesn't need connection to be open
//objMycon1.Open();
MySqlCommand cmd1 = new MySqlCommand(query, objMycon1);
MySqlDataAdapter da = new MySqlDataAdapter(cmd1);
ds = new DataSet();
da.Fill(ds);
objMycon1.Close();
objMycon1.Dispose();//comment if objMycon1 is not IDisposible
}
if (ds.Tables[0].Rows.Count > 0)
{
ddl.DataSource = ds;
ddl.DataTextField = "Name";
ddl.DataValueField = "ID";
ddl.DataBind();
}
}
This is how it should be done.
Hope this helps.
What does (DropDownList)grdViewCInfo.Rows[e.NewEditIndex].Cells[4].FindControl("ddlCountry"); return , is ddl set?
I reckon not. Perhaps there is no "ddlCountry" control in that cell.
Its a curious coincidence that the line,
//grdViewCInfo.Rows[e.NewEditIndex].Cells[4].Controls.Add(ddl);
is commented out below.
Do you have a drop down list in your EditItemTemplate?
Edit: I don't think you are actually in edit mode in the RowEditing event. If you move your code down to the RowCommand,
Then check for the Edit command. Wrap your code in something like,
if(e.CommandName == "Edit")
{
// do your edit here.
}
Though keep your grdViewCInfo.EditIndex = e.NewEditIndex; line, as you need that there.