ASP.net Gridview Itemtemplate Dropdownlist - asp.net

I am using C# ASP.net, and relative new to it, and need to accomplish below.
In my VS2010 web application project I have webform with a Gridview which fetches the data from a table.
In the Grid, I have Commandfiled Button (column1) and Item template with Dropdownlist (column2).
Use case is, user first selects one listitem from 3 list items (H, L and M) and then selects command button.
I am not able to figure out how to extract selected listitem from a selected row
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView2.SelectedRow;
Label4.Text = "You selected " + row.Cells[4].Text + ".";
Label5.Text = "You selected this list item from dropdownlist " + ???? ;
}
Thanks in advance.

The GridViewRow object provides the method FindControl (as do all container controls) to get access to a control in the row by its id. For example, if your DropDownList has an id of MyDropDown, you could use the following to access its selected value:
GridViewRow row = GridView2.SelectedRow;
DropDownList MyDropDown = row.FindControl("MyDropDown") as DropDownList;
string theValue = MyDropDown.SelectedValue;
// now do something with theValue
This is the recommended method for accessing all controls in your GridView. You want to avoid doing things like row.Cells[#] as much as possible, because it easily breaks when you re-arrange or add/remove columns from your GridView.

Related

ASP.Net GridView Edit/Update/Cancel/Delete Events On RowClick

We've got an ASP.Net application that contains a GridView Control that contains row edit functionality.
This allows a user to Edit, Delete, Or Cancel editing on a particular row.
For Example Read Only Mode Looks Like This:
And Edit Mode Looks Like this:
The mechanism that allows the user to enter Edit mode is based on an Edit Button in a template column that changes the selected row from a read only row to an editable row using a RowEditing event something like this:
protected void grdOfMine_RowEditing(object sender, GridViewEditEventArgs e)
{
grdOfMine.EditIndex = e.NewEditIndex;
ReBindDataGrid();
}
Canceling is pretty much the opposite where we have a button click event that changes the row back to ready only mode:
protected void grdOfMine_RowEditing(object sender, GridViewEditEventArgs e)
{
grdOfMine.EditIndex = -1;
ReBindDataGrid();
}
(Apologies to those who are already familiar with this aspect of ASP.Net forms development.)
We've also created a footer row that allows a user to add a new row:
We're looking for a way to extend the ASP.Net GridView control do this without using the buttons to fire the events.
For example:
Allow a user to enter edit mode for a row, by clicking in a cell of any given row and update the selected record say, on an Enter keyboard input event (Instead of the Edit Button).
Delete a record say, on a delete keyboard input event (Instead of the Delete Button).
Add a record in a similar fashion (Instead of the Add Button).
We were attempting this functionality using Infragistics controls, however we had a very tough time getting these to work, so we decided not to use them.
Thanks in advance
I am working on asp.net gridview on webforms and using Gridview RowCommand method of GridView OnRowCommand event for the Buttons View, Edit & Update inside TemplateField.
if (e.CommandName == "EditContract") {
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int SerialNo = (int)gvContract.DataKeys[row.RowIndex].Value;
int rowIndex = ((GridViewRow)((Button)e.CommandSource).NamingContainer).RowIndex;
gvContract.SelectRow(rowIndex);
using (SqlCommand cmd = new SqlCommand("spContractEdit", myObj.DbConnect()))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#RoleName", SqlDbType.Char).Value = Session["RoleName"];
cmd.Parameters.Add("#UnitName", SqlDbType.Char).Value = Session["UnitName"];
cmd.Parameters.Add("#ContrSerialNo", SqlDbType.Int).Value = SerialNo;
dAdapter = new SqlDataAdapter(cmd);
DataTable DtContract = new DataTable();
dAdapter.Fill(DtContract);
}
if (e.CommandName == "UpdateContract") {
lblMessage.Text = "";
lblFile.Text = "";
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int SerialNo = (int)gvContract.DataKeys[row.RowIndex].Value;
using (SqlCommand cmd = new SqlCommand("spContractUpdate", myObj.DbConnect()))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ContrNewRev", SqlDbType.VarChar).Value = ddNewOrRevised.SelectedValue;
cmd.Parameters.Add("#ContractTitle", SqlDbType.VarChar).Value = txtContractTitle.Text;
cmd.Parameters.Add("#FinancerID", SqlDbType.Int).Value = ddFinancer.SelectedValue;
}
This code is working fine when the page loads first time but has 2 problems after that. i.e. 1. It is editing and updating data when the page gets load for the first time but when I try to edit the same row or any other then it doesn't. I know it is because I have defined the !Page.IsPostback method on the Page_Load event but I do not know how to tackle this situation. 2. Problem is How to restrict the gridview row to update only that data whose row is selected?
Please suggest me a solution.
GridView Sample

Dropdownlist values based on another dropdown list

I have a dropdownlist control in which i have added two list items.Both these list items are added manually by me and not from any database.Based on the selection i would like to show another dropdownlist which has a sqldatasource.
I am able to accomplish this if my intial dropdownlist source is also from a database
how do i accomplish this from reading the value of the dropdownlist and populating another dropdown based on the selected value
The second dropdownlist that needs to be populated is going to vary(from differant tables) based on the selected value in the first dropdownlist
Need direction ideas please
Thanks
protected void dropdown1_SelectedIndexChanged(object sender, EventArgs e)
{
string val = dropdown1.SelectedItem.Value;
if(val == "xyz")
SqlDataSource1.SelectCommand = "Select * From Table_1";
else if(val == "abc")
SqlDataSource1.SelectCommand = "Select * From Table_2";
SqlDataSource1.DataBind();
}

Insert "-- Select a Project -- " in a dropdown box

I have a dropdown box in my asp.net web page. I want the dd box to start out on load with "-- Select a Project --" as the text value. The dd box is bound to an EF object at design time -- no custom code (sorry). It has (like a classic Combo Box) an "ID" column (integer) and a display column. When I had a dd box with only one column, the process was simple:
protected void ProjectDropDown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list != null)
list.Items.Insert(0, "--Select a Project--");
}
Here is an image of the EF Datasource:
And Here's an image of the DropDownBox Properties...[ID is an Integer, ProjectNbr is a string]....:
And, since that's hard to read, here's a close-up:
But that doesn't work with a two-element dropdown box. Can anyone give me a hand?
Try this
protected void ProjectDropDown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list != null)
list.Items.Insert(0, new ListItem("--Select a Project--",""));
}
Use the ListControl.AppendDataBoundItems Property and set it to true:
AppendDataBoundItems Documentation
From the documentation: "The AppendDataBoundItems property allows you to add items to the ListControl object before data binding occurs. After data binding, the items collection contains both the items from the data source and the previously added items."

Getting data from GridView on Button_Click

My problem is:
I have a GridView, which is bound to list of declared DTO objects with column of CheckBoxes. Also, I have a "Save" button on the page. My mission concludes in getting all rows, where CheckBox is checked and get the containing data. Unfortunately, row.DataItem = null on Button1_Click, because, I'm using if(!IsPostBack) gw.DataBind() statement (otherwise, I can't get CheckBox status). Could you give me the best practice for solving my problem?
Thank you in advance!
If you do if(!IsPostBack) --> gw.DataBind(), that will reinitialize your GridView and the checkboxes will be set to unchecked again.
In your case, in Button1_Click event, you can loop through each DataRow on your GridView and find the row which has it's checkbox checked and get all the selected row data.
foreach (GridViewRow gvRow in gw.Rows) {
// Find your checkbox
CheckBox chkBox = (CheckBox)gvRow.FindControl("checkBox");
if (chkBox.Checked) {
// Get your values
string value1 = gvRow.Cells[1].Text;
string value2 = gvRow.Cells[2].Text;
// etc...
}
}

Positioning of DDL items?

i have a dropDownList which gets its data from a database. Now after the data has bound, i programmatically add another listItem to the ddl, like so:
protected void ddlEffects_DataBound(object sender, EventArgs e)
{
DropDownList ddl = dwNewItem.FindControl("ddlEffects") as DropDownList;
ddl.Items.Add(new ListItem("","0")); //Adds an empty item so the user can select it and the item doesnt provide an effect
}
It all works, but the problem is that the newly added listItem appears at the bottom of the DDL. I want it to be the first item. I tried making the value 0, but its still at the bottom. Is there any way to put it at the top?
Thanks!
Check into the ddl.Items.Insert method that will allow you to insert items at a specific location.
Like this for example:
using (Entities db = new Entities())
{
ddlDocumentTypes.DataSource = (from q in db.zDocumentTypes where (q.Active == true) select q);
ddlDocumentTypes.DataValueField = "Code";
ddlDocumentTypes.DataTextField = "Description";
ddlDocumentTypes.DataBind();
ddlDocumentTypes.Items.Insert(0, "--Select--");
ddlDocumentTypes.Items[0].Value = "0";
}
Which using EF loads the DDL with items for the database, and then inserts at position zero a new item.

Resources