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());
}
Related
My page which to do this:
I want to connect outside dropdown list to inside of gridview dropdownlist. When selec item from outside dropdownlist, must be change inside dropdown list item automaticaly. I've tried a lot thing to change. Can you give me help. Thanks.
My ASPX page.(Don't answer connected this code)
<asp:GridView ID="GridView4" runat="server" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="Kimlik" GridLines="Horizontal"
onrowdatabound="GridView4_RowDataBound" ForeColor="#333333" Visible="False">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Öd.Nu.">
<EditItemTemplate>
<asp:TextBox ID="TextBox1x" runat="server" Text='<%# Bind("Kimlik") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1x" runat="server" Text='<%# Bind("Kimlik") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Öğrenci Adı Soyadı">
<EditItemTemplate>
<asp:TextBox ID="TextBox2x" runat="server" Text='<%# Bind("OgrenciAdiSoyadi") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2x" runat="server" Text='<%# Bind("OgrenciAdiSoyadi") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Odev Sonucu">
<EditItemTemplate>
<asp:TextBox ID="TextBox3x" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1x" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ödev Sonuç Açıklaması">
<EditItemTemplate>
<asp:TextBox ID="TextBox4x" runat="server" Text='<%# Bind("SonucAciklama") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4x" runat="server" Text='<%# Bind("SonucAciklama") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" ForeColor="White" Font-Bold="True" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
on Selected Index Change Event of Outer drop down add below code
protected void OurterDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView.Rows)
{
DropDownList innerDropdown = (DropDownList)row.FindControl("innedDropedDOwnID");
innerDropdown .ClearSelection(); //making sure the previous selection has been cleared
innerDropdown .Items.FindByValue(OurterDropDown.SelectedValue).Selected = true;
}
}
Make sure you have set AutoPostBack="true" outside DropDownList and then try this code in RowDataBound event:
protected void GridView4_RowDataBound(object sender, GridViewRowEventArgs e)
{
// check if your row is not a Header/Footer row
if (e.Row.RowType == DataControlRowType.DataRow)
{
// get Dropdownlist from gridview
DropDownList DropDownList1x = e.Row.FindControl("DropDownList1x") as DropDownList;
// ddlouter is your outside DropDownList
DropDownList1x.Items.FindByValue(ddlOuter.SelectedValue).Selected = true;
}
}
I have a nested gridview inside another gridview. The parent gridview has a list of tasks, and each task has a list of steps (the child gridview). Each step has a checkbox so once a user is done with a step, he'll check the checkbox and that will fire the CheckChanged event in which I have a stored procedure to update the database so the checked step registers as completed.
I have a CheckChanged event that looks for the step ID of the row the checked checkbox was in, then fires off the stored procedure using the step ID as an input parameter. This works. However, steps can be added, and for some reason, when a check box on an earlier step is clicked, the code that looks for the step ID won't go backwards and recognize the step ID. In other words, if a if the the step ID of a certain task is 20, and it is checked and the event fires off, if I add a step to an earlier task (a task listed higher on the gridview) and that step has an ID of 21, clicking on it will constantly register the step ID as 20, as if the CheckChanged event doesn't recognize a step added to another task. Here is my code:
aspx:
<asp:GridView ID="GridView1"
DataKeyNames="TaskID"
runat="server"
OnRowDataBound="GridView1_OnRowDataBound"
CssClass="DefaultGrid"
onRowCommand="GridView1_RowCommand"
EmptyDataText = "<br/>There are no Tasks in this Project."
AllowPaging="True"
AllowSorting="True"
CellPadding="4"
DataSourceID="SqlDataSource_mp_Display_Tasks_Home"
ForeColor="#333333"
GridLines="None"
AutoGenerateColumns="False">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<RowStyle CssClass=" table-responsive body-content " />
<Columns>
<asp:CommandField ShowSelectButton="False" />
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="Images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display:none">
<asp:GridView ID="GridView2"
runat="server"
onRowCommand="GridView2_RowCommand"
Datakeynames="TaskStepID"
CssClass="ChildGrid"
EmptyDataText="<br/>There are no Steps in this Task."
AutoGenerateColumns="false"
onselectedindexchanged="GridView2_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="TaskStepID" HeaderText="TaskStepID" Visible="true" />
<asp:BoundField DataField="TaskID" HeaderText="TaskID" Visible="false" />
<asp:BoundField DataField="TaskStepTypeID" HeaderText="TaskStepTypeID" Visible="false"/>
<asp:BoundField DataField="TaskStepPriority" HeaderText="Task Step Priority" Visible="false" />
<asp:BoundField ItemStyle-Width="70%" DataField="TaskStepDesc" HeaderText="Step Description" />
<asp:TemplateField HeaderText="Step Completed" ItemStyle-Width="15%" >
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Checkbox ID="TaskStepCompleted"
OnCheckedChanged="TaskStepCompleted_CheckedChanged"
Checked='<%# Eval("TaskStepCompleted") %>'
runat="server"
AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TaskStepComment" HeaderText="TaskStepComment" Visible="false" />
<asp:TemplateField HeaderText="Step Activity" ItemStyle-Width="15%">
<ItemTemplate>
<asp:LinkButton Text="Add" ID="Addstep" runat="server" CommandName="addstep" CommandArgument='<%# Eval("TaskStepID") %>'/>
<asp:LinkButton Text="Edit" ID="Editstep" runat="server" CommandName="editstep" CommandArgument='<%# Eval("TaskStepID") %>'/>
<asp:LinkButton Text="Delete" ID="Deletestep" runat="server" CommandName="deletestep" OnClientClick="return confirm('<%=AlertMe%>');" CommandArgument='<%# Eval("TaskStepID") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TaskID" HeaderText="Task ID" Visible="false"/>
<asp:BoundField DataField="ProjectID" HeaderText="Project ID" Visible="false" />
<asp:BoundField DataField="TaskTypeID" HeaderText="Task Type ID" Visible="false" />
<asp:BoundField DataField="TaskCompleted" HeaderText="Taske Completed?" Visible="false" />
<asp:BoundField DataField="TaskCreationDate" HeaderText="Task Creation Date" Visible="false" />
<asp:BoundField DataField="TaskSubmitterID" HeaderText="Task Submitter ID" Visible="false" />
<asp:BoundField DataField="DepartmentID" HeaderText="DepartmentID" Visible="false" />
<asp:BoundField DataField="TaskDueDateCommentType" HeaderText="Due Date Comment" Visible="false" />
<asp:BoundField DataField="TaskLastUpdatedDate" HeaderText="Task Last Updated Date" Visible="false" />
<asp:BoundField DataField="TaskLastUpdatedUserID" HeaderText="Task Last Updated UserID" Visible="false" />
<asp:BoundField DataField ="TaskSubmitterName" HeaderText="Task Submitter Name" Visible="false" />
<asp:BoundField DataField="TaskLastUpdatedUser" HeaderText="Task Last Updated User" Visible="false" />
<asp:BoundField DataField="DepartmentDesc" HeaderText="Dept" visible="false"/>
<asp:TemplateField HeaderText="Task Description">
<ItemTemplate>
<asp:Label ID="TaskDescription" runat="server" Text='<%# HighlightText(Eval("TaskDescription").ToString()) %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="40%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="% Comp.">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label ID="PercentCompleted" runat="server" Text='<%# (String.IsNullOrEmpty(Eval("PercentCompleted").ToString()) ? "0" : Eval("PercentCompleted")) + " %" %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TaskDueDate" HeaderStyle-HorizontalAlign="Right" HeaderText="Task Due Date" DataFormatString="{0:MM-dd-yyyy}" visible="true"/>
<asp:BoundField DataField="TaskTypeName" HeaderText="Task Type" visible="true" />
<asp:BoundField DataField="DepartmentAbbrev" HeaderText="Dept" Visible="true" />
<asp:TemplateField HeaderText="Activity">
<ItemTemplate>
<asp:LinkButton Text="Edit" ID="Edittask" runat="server" CommandName="edittask" CommandArgument='<%# Eval("TaskID") %>'/>
<asp:LinkButton Text="Delete" ID="Deletetask" runat="server" CommandName="deletetask" OnClientClick="return confirm('Are you sure you wish to Delete this Task?');" CommandArgument='<%# Eval("TaskID") %>'/>
<asp:LinkButton Text="Comments" ID="Detailstask" runat="server" CommandName="detailstask" CommandArgument='<%# Eval("TaskID") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource_mp_Display_Tasks_Home" runat="server" FilterExpression="TaskDescription LIKE '%{0}%'" ConnectionString="<%$ ConnectionStrings:IntelliBaseConnectionString_mp_Display_Projects_Home %>" SelectCommand="mp_Display_Tasks_Home" SelectCommandType="StoredProcedure" ProviderName="System.Data.SqlClient">
<SelectParameters>
<asp:Parameter Name="Incoming_ProjectID" Type="Int32" />
</SelectParameters>
<FilterParameters>
<asp:ControlParameter Name="TaskDescription" ControlID="txtSearchtasks" PropertyName="Text"/>
</FilterParameters>
</asp:SqlDataSource>
cs:
protected void TaskStepCompleted_CheckedChanged(object sender, EventArgs e)
{
// this nested foreach grabs the taskstepID number for the row in which the checkbox was just checked.
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
GridView GridView2 = (GridView)row.FindControl("GridView2");
if (GridView2 != null)
{
foreach (GridViewRow Row in GridView2.Rows)
{
if (Row.RowType == DataControlRowType.DataRow)
{
System.Web.UI.WebControls.CheckBox chk = (System.Web.UI.WebControls.CheckBox)Row.FindControl("TaskStepCompleted");
if (chk.Checked || !chk.Checked)
{
Session["TaskStepID"] = GridView2.DataKeys[Row.RowIndex]["TaskStepID"].ToString();
}
}
}
}
}
}
// autopost back the check box to run the stored procedure
var TaskStepID = Session["TaskStepID"].ToString();
var ProjectID = Session["ProjectID"].ToString();
using (var conn = new SqlConnection("Data Source=orlandosql1;Initial Catalog=IntelliBase;Persist Security Info=True;User ID=trainingsurveys_webuser;Password=C#mb3rSQL;"))
using (SqlCommand cmd = new SqlCommand("dbo.mp_Task_Step_Completed_Toggle", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#TaskStepID", SqlDbType.Int).Value = TaskStepID;
cmd.Parameters.Add("#AdminUserID", SqlDbType.Int).Value = "10";
cmd.Parameters.Add("#LogActionItemID", SqlDbType.Int).Value = "15";
cmd.Parameters.AddWithValue("#DTStamp", SqlDbType.DateTime.ToString("d")).Value = DateTime.Now.ToString("d");
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Response.Redirect("Tasks.aspx?id=" + ProjectID.ToString());
}
}
I tried my best to describe the issue. To recap: nested gridview has rows with check boxes. Clicking the checkbox automatically updates db tables, but regardless of check box row, the CheckedChanged code will only register the ID of the most recent ID. Any insight is appreciated.
Carlos
If I understand correctly, I believe your issue comes with how you think you are grabbing the TaskStepID of your GridViewRow. You are doing a lot of unnecessary work. Instead of iterating every row of both GridViews, just grab the GridViewRow of the CheckBox that was just clicked.
CheckBox cb = (CheckBox)sender;
GridViewRow row = (GridViewRow)cb.NamingContainer;
GridView gv = (GridView)row.NamingContainer;
string taskStepID = gv.DataKeys[row.RowIndex].Value.ToString();
Notice how by iterating each row like you were, you were always getting the TaskStepID of the last row. So when you added a row before it, it was using the last row instead of the one you expected.
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"]));
SQL Server table structure:
ChapName varchar(200)
Status varchar(1)
Requirement:
I want to display checkbox in an ASP.NET gridview from Visual Studio 2010
if the value of status column is T, let it be checked and unchecked otherwise.
but it shows only textbox.
I have tried <asp:templatefield> and <asp:itemtemplate> but it throws error if I try to bind this checkbox.
any sample code is required as I am beginner in this field.
The code I tried:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
CheckBox c = (CheckBox)GridView1.FindControl("ChkStatus");
TextBox TB = (TextBox)GridView1.FindControl("Status");
//Response.Write(TB.Text);
if (TB.Text == "T")
{
c.Checked = true;
}
else
{
c.Checked = false;
}
}
The error I got
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the
error and where it originated in the code.
Exception Details:
System.NullReferenceException: Object reference not set to an instance
of an object.
Aspx markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Comp,QTypeCode" DataSourceID="SDS_QType_Edit"
BackColor="White" BorderColor="#DEDFDE" BorderStyle="None"
BorderWidth="1px"
CellPadding="4" ForeColor="Black" GridLines="Vertical"
AllowPaging="True" AllowSorting="True"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowdatabound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowEditButton="True" ShowSelectButton="True" />
<asp:BoundField DataField="QTypeCode" HeaderText="QTypeCode"
SortExpression="QTypeCode" InsertVisible="False"
ReadOnly="True" />
<asp:BoundField DataField="Descr" HeaderText="Descr" SortExpression="Descr" />
<asp:CheckBoxField DataField="AnsReq" HeaderText="AnsReq" ReadOnly="True"
SortExpression="AnsReq" />
<asp:CheckBoxField DataField="OptionPrint" HeaderText="OptionPrint"
ReadOnly="True" SortExpression="OptionPrint" />
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
<asp:BoundField DataField="TransDate" HeaderText="TransDate"
SortExpression="TransDate" />
<asp:BoundField DataField="UserName" HeaderText="UserName"
SortExpression="UserName" />
<asp:TemplateField HeaderText="Check Box" >
<ItemTemplate>
<asp:CheckBox ID ="ChkStatus" Text="text" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle Wrap="False" />
<EmptyDataRowStyle Wrap="False" />
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle Wrap="False" BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle Wrap="False" BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White"
Wrap="False" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
Assume you have grid defined as below on asmx
<asp:GridView ID="GridView1" runat="server"
onrowdatabound="GridView1_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ChapName" HeaderText="ChapName" />
<asp:TemplateField HeaderText="Status" Visible ="false">
<ItemTemplate>
<asp:Label ID="Status" runat="server" Text='<%# Bind("Status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Check Box" >
<ItemTemplate>
<asp:CheckBox ID ="ChkStatus" Text="text" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
on Row Data Bound event you can find controls as below
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
CheckBox c = e.Row.FindControl("ChkStatus") as CheckBox;
Label lbl = e.Row.FindControl("Status") as Label;
if (c!= null && lbl != null )
{
c.Checked = (lbl.Text == "T");
}
}
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 :)