Add a drop down list to a GridView cell - c#

I want to make a column in the GridView a drop down list so the user can select an option from this list.
GridView code:
<asp:GridView style="float:left"
ID="gvBookings"
ShowHeaderWhenEmpty="true"
CssClass="tblResults"
runat="server"
OnRowDataBound="gvBooking_RowDataBound"
DataKeyField="ID"
AutoGenerateColumns="false"
allowpaging="false" />
<Columns>
<asp:BoundField DataField="FinishTime" HeaderText="Finish Time"></asp:BoundField>
<asp:BoundField DataField="TimeSpentName" HeaderText="Time Spent By"></asp:BoundField>
</Columns>
</asp:GridView>
Code Behind:
protected void gvBooking_RowDataBound(object sender, GridViewRowEventArgs e)
{
BHTaskClass.BookingTask booking = (BHTaskClass.BookingTask)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
int count = 1;
foreach (TableCell c in e.Row.Cells)
{
if (count == 1)
{
string FinishTime = booking.FinishTime.HasValue ? booking.FinishTime.Value.ToString("hh':'mm") : "";
c.Text = "<input type=\"text\" id=\"txtFinishTime" + booking.ID + "\" style=\"width:70px\" type=\"text\" onblur=\"UpdateFinishTime(" + booking.ID + ",this.value)\" value=\"" + FinishTime + "\" >";
}
count++;
}
}
}
In the code behind I changed the cell for FinishTime to a textbox. And when the user enters a value in here it calls a function that updates the database.
How do I change the cell to become a drop down menu? Can I do it did in the code behind like I created the textbox or would it be better to change the Boundfield in the GridView

I think you have to start using TemplateField instead of BoundField. Then you can put a TextBox and/or DropDownList directly in the GridView. You can then save the changes with the OnRowCommand event.
<asp:GridView ID="gvBookings"
runat="server"
OnRowDataBound="gvBookings_RowDataBound"
OnRowCommand="gvBookings_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1"
runat="server"
Text='<%# Eval("FinishTime") %>'></asp:TextBox>
<asp:LinkButton ID="LinkButton1"
runat="server"
CommandName="saveTextBox"
CommandArgument='<%# Container.DataItemIndex %>'>Save</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1"
runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
protected void gvBookings_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//find the dropdownlist in the current row with findcontrol and cast back to one
DropDownList dropDownList = e.Row.FindControl("DropDownList1") as DropDownList;
//add some listitems
dropDownList.Items.Insert(0, new ListItem("Text A", "A"));
dropDownList.Items.Insert(1, new ListItem("Text B", "B"));
dropDownList.Items.Insert(2, new ListItem("Text C", "C"));
//select a value in the dropdown
dropDownList.SelectedValue = "B";
}
}
protected void gvBookings_RowCommand(object sender, GridViewCommandEventArgs e)
{
//check the commandname
if (e.CommandName == "saveTextBox")
{
//convert the commandargument to a row number
int rowNumber = Convert.ToInt32(e.CommandArgument);
//find the textbox in the current row with findcontrol and cast back to one
TextBox textBox = gvBookings.Rows[rowNumber].FindControl("TextBox1") as TextBox;
//do stuff with the textbox value
Label1.Text = textBox.Text;
}
}

Related

Find Control on RowDataBound-Event returns as NULL/Empty

I am trying to get text value of the selected row from my GridView using FindControl, but the FindControl always returns as NULL.
.ASPX Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CID" DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="CID" HeaderText="CID" InsertVisible="False" ReadOnly="True" SortExpression="CID" />
<asp:BoundField DataField="CountryID" HeaderText="CountryID" SortExpression="CountryID" />
<asp:TemplateField HeaderText="CountryName" SortExpression="CountryName">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CountryName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("CountryName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C# Code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txt = e.Row.FindControl("TextBox1") as TextBox;
string name = txt.Text; // returns as NULL
}
}
Can anybody point out what I am doing wrong here or is there any other way of doing this? I wanted to get value of the CountryName from the above GridView when select button is clicked.
As #AlexKurryashev above comment you have to check/find control from EditTemplate mode of GridView:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// check if its not a header or footer row
if (e.Row.RowType == DataControlRowType.DataRow)
{
// check if its in a EditTemplate
if (e.Row.RowState == DataControlRowState.Edit)
{
TextBox txt = e.Row.FindControl("TextBox1") as TextBox;
string name = txt.Text;
}
}
}
OR
You can use OnRowCommand event to get value from select button click as follows:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
// get row where clicked
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
Label txt = row.FindControl("Label1") as Label;
string name = txt.Text;
}
}
Thank you both! I was able to get data from "ItemTemplate". But i used a different event this time.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
{
Label txt = GridView1.SelectedRow.FindControl("Label1") as Label;
string name = txt.Text;
Label2.Text = name;
Session["Name"] = name;
Response.Redirect("check.aspx");
}
}
I was able to get the data from Item HeaderTemplate by using this code.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
{
GridViewRow headerrow = GridView1.HeaderRow;
DropDownList ddlId = (DropDownList)headerrow.Cells[0].Controls[1].FindControl("ddlId ");
string headerid = ddlId.SelectedValue;
}
}

Add a checkboxes column to a gridview

I have a gridview that displays data coming from an SQL data source (stored procedure) and I want to add a checkboxex column to it, here is my code:
TemplateField field = new TemplateField();
field.HeaderText = "Exporter ?";
gv.Columns.Add(field);
CheckBox cb = new CheckBox();
cb.Visible = true;
The problem is that I don't know how to add a checkbox to the TemplateField that I added to my gridview columns.
1) Add below code to GridView columns.
<asp:TemplateField HeaderText="CheckBoxColumn" Visible="False">
<ItemTemplate>
<asp:CheckBox ID="checkBox" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
2) Make checkbox column visible dynamically by adding OnRowDataBound event or just looping through GridView.Rows
int indexOfCBColumn = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[indexOfCBColumn].Visible = true;
}
foreach(GridViewRow row in GridView1.Rows) {
if(row.RowType == DataControlRowType.DataRow) {
row.Cells[indexOfCBColumn].Visible = true;
}
}
Thanks!!
You can add the code below into the GridView Columns.
<asp:templatefield HeaderText="Check Box">
<itemtemplate>
<asp:checkbox ID="cb" runat="server"></asp:checkbox>
</itemtemplate>
</asp:templatefield>

Access gridview row's data from LinkButton inside that row

Each row of the GridView is populated from a SQL DB.
Each row has a LinkButton that brings up a popup.
In the code behind I want to have access to the DataField="RCID"
I guess I'd like to attach the RCID field to the Upload link so when it's clicked I have access to the RCID within the function that handles the onclick.
How do I get this rows RCID?
<asp:GridView ID="GridView1" runat="server"
OnPageIndexChanging="GridView1_PageIndexChanging"
GridLines="Horizontal" AllowPaging="true" OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="RCID" DataField="RCID" Visible="false"></asp:BoundField>
<asp:BoundField HeaderText="RC Type" DataField="RCType"></asp:BoundField>
<asp:BoundField HeaderText="Channel" DataField="Channel"></asp:BoundField>
<asp:BoundField HeaderText="Total" DataField="Total"></asp:BoundField>
<asp:BoundField HeaderText="Expired In 30 Days" DataField="ExpiredIn30Days"></asp:BoundField>
<asp:BoundField HeaderText="Expired In 60 Days" DataField="ExpiredIn60Days"></asp:BoundField>
<asp:BoundField HeaderText="Expired In 90 Days" DataField="ExpiredIn90Days"></asp:BoundField>
<asp:BoundField HeaderText="Last Updated" DataField="LastUpdated"></asp:BoundField>
<asp:TemplateField HeaderText="Management">
<ItemTemplate>
<asp:LinkButton runat="server" ID="Upload" Text="Upload" CommandName="Upload" ></asp:LinkButton> |
<asp:LinkButton runat="server" ID="Details" Text="Details" CommandName="Details"></asp:LinkButton> |
<asp:LinkButton runat="server" ID="Files" Text="Files" CommandName="Files"></asp:LinkButton> |
<asp:LinkButton runat="server" ID="Edit" Text="Edit" CommandName="Edit"></asp:LinkButton> |
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Possible solution would be as follows:
Add RowCreated and RowCommand events for GridView
In RowCreated event, I have set “Visible” property to “false” for first column for both header and data row.
In RowCommand event, CommandName is checked first and then index for select command is retrieved. I have retrieved the row for that index and then retrieved the text in the specified row cell.
check this example:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Visible = false;
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Visible = false;
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
Label1.Text = (row.Cells[0].Text);
}
}
Second approach:
Assign command argument to your hidden field value. This will reduce another efforts. check this way:
<asp:TemplateField HeaderText="Action3" Visible="false">
<ItemStyle HorizontalAlign="Center"></ItemStyle>
<ItemTemplate>
<asp:LinkButton ID="lnkretqty" runat="server" Text="Return Qty" CommandName="RETQTY" ToolTip="Click here to Add Return Qty Entry"
CommandArgument='<%# Container.DataItemIndex %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Code Behind code
protected void gvsearch_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "SRCSELREC")
{
Int32 rowind = Convert.ToInt32(e.CommandArgument.ToString());
string val = ((Label)gvgpitemdtl.Rows[rowind].FindControl("d")).Text.ToString();
}
}
catch (Exception ex)
{
General.MessageBox(this.Page, "Error at Gridview Row Command : " + ex.Message.ToString());
return;
}
}
References:
Way of getting Hidden column value in GridView
How to Get Hidden Column values in GridView
To Find Control in GridView on RowCommand event in asp.net
How to hide GridView column and retrieve value from hidden column cell in ASP.NET
Add CommandArgument='<%# Eval("RCID") %>' in the linkbutton's markup:
<asp:LinkButton runat="server" ID="Upload" Text="Upload" CommandName="Upload" CommandArgument='<%# Eval("RCID") %>'/>
Now, in the code behind of the handler, just read the CommandArgumentproperty of the passed GridViewCommandEventArgs parameter:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Upload")
{
var valueOfRCID = e.CommandArgument;
}
}
mshsayem may be right but note you can also just grab the value from within the click event as follows
<asp:LinkButton runat="server" ID="Upload" Text="Upload" OnClick="Upload_Click" CommandArgument='<%# Eval("RCID") %>'/>
protected void Upload_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)(sender);
string RCID = btn.CommandArgument;
}

Hiding dropdownlist in templatefield in gridview asp.net C# after insert into the database

I have a problem, I would like after the value from the dropdown list is picked up, inserted into the db I would like it to hide the dropdown list and just show the grade of the product that the user rated, as on the two following pictures:
This is the first picture showing how the user needs to insert the grade into the db of the product:
The result after should be as following:
The dropdownlist should now be invisible to the user which rated the product. I have tried using the RowDataBound event and the following code:
if (e.Row.RowType == DataControlRowType.DataRow)
{
hsp_Narudzbe_Detalji_Result k = (hsp_Narudzbe_Detalji_Result)e.Row.DataItem;
if (k.Ocjena!=null)
{
e.Row.Cells[4].Text = k.ocjena;
}
}
But it doesn't works, it shows the grade just once, and when I press the button for grading the product, the dropdown list is back... :/
Can someone help me out with this?
Edit (aspx code of the page):
<asp:GridView ID="gridDetaljiNarudzbe" AutoGenerateColumns="false" AllowPaging="true" PageSize="10" runat="server" OnRowCommand="gridDetaljiNarudzbe_RowCommand" OnPageIndexChanging="gridDetaljiNarudzbe_PageIndexChanging" OnRowDataBound="gridDetaljiNarudzbe_RowDataBound">
<Columns>
<asp:BoundField DataField="Naziv" HeaderText="Naziv" />
<asp:BoundField DataField="Sifra" HeaderText="Šifra" />
<asp:BoundField DataField="Cijena" HeaderText="Cijena" />
<asp:BoundField DataField="Kolicina" HeaderText="Količina" />
<asp:TemplateField HeaderText="Ocjena">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnOcijeni" title="Ocijeni proizvod" CommandName="OcijeniCommand" CommandArgument='<%#Eval("ProizvodID") + ";" +((GridViewRow) Container).RowIndex%>' runat="server"><img src="../images/ocijeni.png" /></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The grades are loaded like this:
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList drop = e.Row.FindControl("DropDownList1") as DropDownList;
drop.Items.Add(new ListItem(""));
drop.Items.Add(new ListItem("1"));
drop.Items.Add(new ListItem("2"));
drop.Items.Add(new ListItem("3"));
drop.Items.Add(new ListItem("4"));
drop.Items.Add(new ListItem("5"));
}
Try something like this,
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = e.Row.Cells[4].FindControl("DropDownList2") as DropDownList;
if (ddl != null)
{
// if (your_condition == true)
//{
ddl .Visible = false;
//}
}
}
}
Hi Make your item template like below :
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
<asp:Label ID="gvlblddlVal" runat="server" Text='<%#((YourEntityClassName)Container.DataItem).ddlVal %>'></asp:Label>
</ItemTemplate>
After that
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = e.Row.Cells[4].FindControl("DropDownList2") as DropDownList;
Label lblddl = e.Row.Cells[4].FindControl("gvlblddlVal") as Label;
if (!string.IsNullOrEmpty(lblddl.Text))
{
ddl.Visible = false;
lblddl.Visible = true;
}
else
{
ddl.Visible = true;
lblddl.Visible =false;
}
}
}
Hope it helps

How to get the modified textbox value in c#?

I used a textbox in gridview to bind a value from db during pageload..
The problem is when i change the textbox value i could not get the modified value in c#, instead it gives the original value which had been there before i modified..
I am using nested GridViews...
kindly help me..
<asp:TemplateField HeaderText="Singles" >
<ItemTemplate>
<asp:HiddenField ID="hidqua" runat="server" Value='<%#bind("QualityName") %>' />
<asp:HiddenField ID="hidfau" runat="server" Value='<%#bind("FaultName") %>' />
<asp:TextBox ID="asptxtsingleg" runat="server" Text='<%# bind("singles") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
and below is my c# Coding
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "update")
{
foreach (GridViewRow row in grdInspection.Rows)
{
HiddenField hv = (HiddenField)row.FindControl("hidval");
GridView txtsi = (GridView)row.FindControl("grdInsiewChid");
foreach (GridViewRow row1 in txtsi.Rows)
{
HiddenField htn = (HiddenField)row1.FindControl("hdnPLength");
GridView nesgrid = (GridView)row1.FindControl("GridView1");
foreach (GridViewRow row2 in nesgrid.Rows)
{
HiddenField qn = (HiddenField)row2.FindControl("hidqua");
TextBox t = (TextBox)row2.FindControl("asptxtsingleg");
}
}
}
}
}
Assuming you are using button to fire the RowCommand event.
<asp:TemplateField HeaderText="Singles">
<ItemTemplate>
<asp:TextBox ID="asptxtsingleg" runat="server" Text='<%# Eval("singles") %>' Width="120px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button ID="BtnEdit" runat="server" Text="Update" CommandName="updateData" CommandArgument='<%# Eval("Your_ID") %>' />
</ItemTemplate>
</asp:TemplateField>
Code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "updateData")
{
//int i = Convert.ToInt32(e.CommandArgument);
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
TextBox tb = (TextBox)row.FindControl("asptxtsingleg");
}
}
You can use below code to get the text box value in RowUpdating event
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
TextBox t= (TextBox)row.FindControl("asptxtsingleg");

Categories

Resources