My gridview is like this but I am getting error when I select view button to find primary key value column on selected index changed. Please help me to solve the issue.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns >
<asp:TemplateField >
<ItemTemplate >
<asp:Button ID="btnViewComments" Text ="View Comments" runat ="server" CommandName ="select" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField ="forumId" Visible ="false" />
<%--<asp:CommandField ButtonType ="Button" ShowSelectButton ="true" SelectText ="View Comments"/>--%>
<asp:TemplateField HeaderText ="Question">
<ItemTemplate >
<asp:TextBox ID ="txtQuestion" Text ='<%#Eval("question")%>' runat ="server" TextMode ="MultiLine" Height="100" Width ="350"></asp:TextBox>
<%-- <%#Eval("question")%>--%>
</ItemTemplate>
<%--<EditItemTemplate >
<asp:TextBox ID ="txtQuestion" Text ='<%#Eval("question")%>' runat ="server" TextMode ="MultiLine" ></asp:TextBox>
</EditItemTemplate>--%>
</asp:TemplateField>
<asp:TemplateField HeaderText="Poster Name">
<ItemTemplate >
<%#Eval("posterName") %>
</ItemTemplate>
<EditItemTemplate >
<asp:Label ID ="lblPosterName" Text ='<%#Eval("posterName") %>' runat ="server" ></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate >
<%#Eval("dateTim") %>
</ItemTemplate>
<EditItemTemplate >
<asp:Label ID ="lblDateTime" Text ='<%#Eval("dateTim") %>' runat ="server" ></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
my code is.....
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
Int64 forumId = (Int64)GridView1.SelectedValue;
Session["forumId"] = forumId;
Response.Redirect("Thread.aspx");
}
catch (Exception)
{
throw;
}
}
First you have to define field name in grid view declaration that which field you want to make datakey. for example if you want "forumId" datakey.than
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
DataKeyNames="forumId">
and than you can access in this way
int intforumid = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
Int64 forumId = Convert.ToInt64(GridView1.SelectedRow.Cells[1].Text);
Session["forumId"] = forumId;
Response.Redirect("Thread.aspx");
}
catch (Exception)
{
throw;
}
}
Looks like you just need to set DataKeyNames property to forumId like;
<asp:GridView DataKeyNames = "forumId" ...
you can set DataKeyNames as forumId like below
<asp:GridView ID="GridView1" runat="server" DataKeyNames = "forumId" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
Since you haven't give any data key names in current solution GridView1.SelectedValue will not contain the value you expected
You would need to specify the unique column name in the gridview to be set under the Datakey tab.
From there, you would need to invoke the _selectedIndexChanged method on the behind page code.
If you are not using gridview select event in your page.cs code then you just remove OnSelectedIndexChanged="GridView1_SelectedIndexChanged" from the aspx code of page of gridview.
Related
I have been looking all over web and testing what I think would work. I feel close but I guess not close enough. I need help pull the data in. The button click is to submit/insert data into the DB which I have not completed that part. Right now I am working on just getting data from the Gridview and need help.
The Update Button is outside the Gridview. I want end user to complete GridView then click update to submit data from Gridview to database.
Here is ASPX
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="dsSnumbers" OnRowDataBound="GridView1_RowDataBound"
GridLines="Horizontal" BackColor="White" BorderColor="#336666" BorderStyle="Double"
BorderWidth="3px">
<Columns>
<asp:TemplateField HeaderText="SerialNumber">
<ItemTemplate>
<asp:TextBox ID="TextBox1" BackColor="BurlyWood" runat="server" Text='<%# Eval("SerialNumber") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList ID="DdStatus" runat="server" DataSourceID="Ds_Variables" DataTextField="Status" DataValueField="Value" Height="16px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dept">
<ItemTemplate>
<asp:DropDownList ID="DdDept" runat="server" DataSourceID="Ds_Variables" DataTextField="Status" DataValueField="Value" Height="16px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Update">
<ItemTemplate>
<asp:CheckBoxList ID="CheckBoxList1" RepeatLayout="Flow" RepeatDirection="Horizontal"
runat="server">
<asp:ListItem Text="Modify?" Value="1">
</asp:ListItem>
</asp:CheckBoxList>
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#333333" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#333333" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#487575" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#275353" />
<%-- <EmptyDataTemplate></EmptyDataTemplate>--%>
</asp:GridView>
And here is the .CS side
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
int RI = g1.RowIndex;
//SqlConnection con = new SqlConnection(connStr);
TextBox test = (TextBox)g1.Cells[0].FindControl("TextBox1");
TextBox test1 = (TextBox)g1.Cells[1].FindControl("TextBox1");
GridViewRow Grow = (GridViewRow)g1.NamingContainer;
TextBox txtledName = (TextBox)Grow.FindControl("TextBox1");
DropDownList testdd1 = (DropDownList)g1.Cells[0].FindControl("DdStatus");
DropDownList testdd2 = (DropDownList)g1.Cells[1].FindControl("DdStatus");
string test1324 = g1.Cells[1].Text;
string test2 = g1.Cells[2].Text;
string test3 = g1.Cells[3].Text;
}
}
Update:
When I run the below I can read the button click whether it is checked or not. However the textbox and dropdown still do nothing. I show ONLY rindex is pulling values. None of the others.
foreach (GridViewRow row in GridView1.Rows)
{
int rindex = row.DataItemIndex;
//string Test = ((TextBox)(row.Cells[0].Controls[0])).Text;
TextBox IDNum = (TextBox)row.FindControl("TextBox1");
string textBox1 = ((TextBox)row.FindControl("TextBox1")).Text;
string ddl1 = ((DropDownList)row.FindControl("DdStatus")).SelectedValue;
string ddl2 = ((DropDownList)row.FindControl("DdDept")).SelectedValue;
int ddl1231 = ((DropDownList)row.FindControl("DdStatus")).SelectedIndex;
int ddl1232 = ((DropDownList)row.FindControl("DdDept")).SelectedIndex;
I have tried several so called answers for this and it has me lost. I am simply trying to default a TextBox Text value with today's date and time, but I cannot find the control when I click LinkButton with CommandName "Edit".
Here is my gridview...
<asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3"
DataSourceID="sdsSignInRegister" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" GridLines="Vertical" OnRowCommand="gvSignInRegister_RowCommand1">
<Columns>
<asp:TemplateField HeaderText="Returned" SortExpression="DateTimeReturned">
<EditItemTemplate>
<asp:TextBox ID="txtReturned" runat="server"></asp:TextBox>
<asp:ImageButton runat="Server" ID="calImg" ImageUrl="~/images/Calendar_scheduleHS.png" AlternateText="Click to show calendar" CausesValidation="False" />
<asp:RequiredFieldValidator ID="rfv1" runat="server" SetFocusOnError="true" ValidationGroup="vg1" ControlToValidate="txtReturned" ErrorMessage="Required"></asp:RequiredFieldValidator>
<ajaxToolkit:CalendarExtender ID="ce1" runat="server" PopupButtonID="calImg" Enabled="true" Format="dd/MM/yyyy" TargetControlID="txtReturned" PopupPosition="TopRight" OnClientDateSelectionChanged="AppendTime"></ajaxToolkit:CalendarExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text='<%# Eval("DateTimeReturned","{0:dd/MM/yyyy HH:mm}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:Button ID="btnCAN" runat="server" CausesValidation="false" CommandName="Cancel" Text="CANCEL" />
<asp:Button ID="btnUPD" runat="server" ValidationGroup="vg1" CausesValidation="true" CommandName="Update" Text="UPDATE" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="btnEDT" runat="server" CausesValidation="false" CommandName="Edit" CommandArgument='<%# Container.DataItemIndex %>' Text="SIGN IN" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
The LinkButton btnEDT works and puts the gridview in edit mode. But in code behind I cannot find "txtReturned".
This is what I've tried so far...
protected void gvSignInRegister_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
int rowIdx = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvSignInRegister.Rows[rowIdx];
if (row != null && row.RowType == DataControlRowType.DataRow)
{
TextBox tb = (TextBox)row.FindControl("txtReturned");
if (tb != null) tb.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
//I've tried this too but it does not work. Interestingly, it does not crash, so cells[4] must exist!
//row.Cells[4].Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
}
}
}
For some reason the rowIdx is always 0. Why? I thought a row index of 0 meant the header of the gridview control.
I've also tried using the NamingContainer that most other people have suggested in other posts, but that returns a blank (I suspect new?) GridViewRow.
ie
GridViewRow row = (GridViewRow)((GridViewRow)(e.CommandSource).NamingContainer);
UPDATE
I found this, which is exactly the problem I am having, but the solution via the RowEditing still does not find the textbox!
However the RowDataBound() solved it! Read my answer below.
The answer was in getting into the editmode version of the GridView itself and then find the control!
As per this post...
<asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3"
DataSourceID="sdsSignInRegister" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" GridLines="Vertical" OnRowDataBound="gvSignInRegister_RowDataBound">
<Columns> ...etc...
protected void gvSignInRegister_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
TextBox tb = (TextBox)e.Row.FindControl("txtReturned");
if (tb != null) tb.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
}
}
}
Use Container.DisplayIndex instead of Container.DataItemIndex
But I dont think you will get textBox control if you are placing it in EditItemTemplate
If your expectation is editing operation then please use the below code
HTML
<asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" OnRowEditing="gvSignInRegister_RowEditing" OnRowCancelingEdit="gvSignInRegister_RowCancelingEdit" OnRowUpdating ="gvSignInRegister_RowUpdating" GridLines="Vertical">
<Columns>
<asp:TemplateField HeaderText="Returned" SortExpression="DateTimeReturned">
<EditItemTemplate>
<asp:TextBox ID="txtReturned" Text='<%#Bind("DateTimeReturned", "{0:dd/MM/yyyy HH:mm}")%>' runat="server"></asp:TextBox>
<asp:ImageButton runat="Server" ID="calImg" ImageUrl="~/images/Calendar_scheduleHS.png" AlternateText="Click to show calendar" CausesValidation="False" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text='<%# Eval( "DateTimeReturned","{0:dd/MM/yyyy HH:mm}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
Code Behind:
protected void gvSignInRegister_RowEditing(object sender, GridViewEditEventArgs e)
{
gvSignInRegister.EditIndex = e.NewEditIndex;
List<QuotationDetail> itemList = (List<QuotationDetail>)ViewState["ItemList"];
gvSignInRegister.DataSource = itemList;
gvSignInRegister.DataBind();
}
protected void gvSignInRegister_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
}
protected void gvSignInRegister_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
var txtQty = (TextBox)gvSignInRegister.Rows[e.RowIndex].FindControl("txtQuantity");
decimal qty = 0;
decimal.TryParse(txtQty.Text, out qty);
if (qty < 0)
{
lblErrorSummary.InnerText = "Please provide valid Quantity";
lblErrorSummary.Visible = true;
return;
}
itemList[e.RowIndex].Quantity = qty
ViewState["ItemList"] = itemList;
gvSignInRegister.EditIndex = -1;
gvSignInRegister.DataSource = itemList;
gvSignInRegister.DataBind();
}
This is what I have done for nested gridview :
The jQuery I have used to maintain this show hide is as:
<script type="text/javascript">
// Method for managing opening of gridview on + image and - image
$("[src*=plus]").live("click", function() {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "../Image/minus.gif");
});
$("[src*=minus]").live("click", function() {
$(this).attr("src", "../Image/plus.gif");
$(this).closest("tr").next().remove();
});
</script>
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" DataKeyNames="num"
AutoGenerateColumns="False" Style="font-size: x-small" OnSelectedIndexChanging="GridView1_SelectedIndexChanging"
OnRowCancelingEdit="GridView1_RowCancelling" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand"
OnRowDeleting="GridView1_RowDeleting" ShowFooter="True"
OnRowEditing="GridView1_RowEditing" OnRowDataBound="GridView1_RowDataBound" OnSorting="GridView1_Sorting"
AllowSorting="true">
<RowStyle BackColor="#E3EAEB" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="../Image/plus.gif" />
<asp:Panel ID="pnlOrders" style="display:none;">
<asp:GridView ID="GridView3" runat="server" CellPadding="4" ForeColor="#333333" DataKeyNames="sno"
OnRowCancelingEdit="GridView3_RowCancelling" OnRowUpdating="GridView3_RowUpdating"
OnRowEditing="GridView3_RowEditing" AutoGenerateColumns="False" Style="font-size: x-small">
<RowStyle BackColor="#E3EAEB" />
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField>
<HeaderTemplate>
Detailed Head
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="empdetails" Width="200px" runat="server" Text='<%# Eval("Details") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtempdetail" Width="200px" runat="server" MaxLength="9" Text='<%# Eval("Details") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="sal" HeaderText="salary" />
<asp:CommandField ShowEditButton="true" EditText="Edit" />
</Columns>
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="View" runat="server" Text="View" CommandName="view"
CommandArgument='<%#Container.DataItemIndex+1 %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Age</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblage" Width="80px" runat="server" MaxLength="4" Text='<%# Eval("age") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtage" runat="server" Text='<%# Eval("age") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
BloodGroup</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblBloodGroup" Width="100px" runat="server" MaxLength="9" Text='<%# Eval(" BloodGroup") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBloodGroup" runat="server" Text='<%# Eval(" BloodGroup") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" SelectText="Select" />
<asp:CommandField DeleteText="Reject" ShowDeleteButton="True" />
<asp:CommandField ShowEditButton="true" EditText="Edit" />
</Columns>
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
On server side this is what I am doing:
protected void GridView3_RowEditing(object sender, GridViewEditEventArgs e)
{
DataSet ds = new DataSet();
tBL objBL = new tBL();
GridViewRow editedRow = GridView1.Rows[e.NewEditIndex];
//now search row for your control...
GridView GridView3 = (GridView)editedRow.FindControl("GridView3");
GridView3.EditIndex = e.NewEditIndex;
objtxtToTableBL.ViewBL(dt);
GridView3.DataSource = dt;
GridView3.DataBind();
}
protected void GridView3_RowCancelling(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
}
protected void GridView3_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
I am binding the nested gridview on rowdatabound of GridView1 and that works fine.
The problem with all this is when I click on the edit button of innergridview(child) it get hide as the page postback .
What should I do so that when I click on its edit button the child gridview remains open and it gets hides only when I click on minus button. Please help it has already taken 3 days of mine.
I've a grid view with three columns Employee name Employee details and Employee age.
I want to add a check box at each row and after selection of each check box i want to fire a insert query associated to that employee.
Can you tell me how to add this dynamic functionality to the grid view.
also if we use <%# EVAL %> i don't know how to implement it with checkbox.
ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
<asp:BoundField DataField="details" HeaderText="details"
SortExpression="details" />
<asp:BoundField DataField="age" HeaderText="age" SortExpression="age" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="OK" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:connApps %>"
SelectCommand="SELECT [name], [details], [age] FROM [tblA]">
</asp:SqlDataSource>
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Selected item name:<br>";
foreach (GridViewRow item in GridView1.Rows)
{
CheckBox chk = (CheckBox)item.FindControl("CheckBox1");
if (chk != null)
{
if (chk.Checked)
{
Label1.Text += item.Cells[1].Text + "<br>";
}
}
}
}
Output:
Here is an example ,
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#336699" BorderStyle="Solid" BorderWidth="1px"
CellPadding="0" CellSpacing="0" DataKeyNames="CategoryID" Font-Size="10"
Font-Names="Arial" GridLines="Vertical" Width="40%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkStatus" runat="server"
AutoPostBack="true" OnCheckedChanged="chkStatus_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("Approved")) %>'
Text='<%# Eval("Approved").ToString().Equals("True") ? " Approved " : " Not Approved " %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
</Columns>
<HeaderStyle BackColor="#336699" ForeColor="White" Height="20" />
For more information , check Here !
you can use TemplateFields for the GridView:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:CheckBox ID="myCheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and in code behind use below code:
ClusterName = GV.Rows(1).Cells(2).FindControl("myLabelinTheGridViewTemplateField")
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());
}