Pass data from onRowDataBound to onRowUpdating in ASP Web Forms - c#

I have a GridView on aspx that accepts OnRowDataBound and OnRowUpdating. The AutoGenerateColumns is set to true. My task is to update the textbox to dropdown.
On RowDataBound, I created a sample code snippet to change the text box to dropdown list:
protected void gv_OnRowDataBound(obejct sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
DropDownList ddlEdit = new DropdownList();
ddl.Items.Add(new ListItem("Test1", "Test1"));
ddl.Items.Add(new ListItem("Test2", "Test2"));
e.Row.Cells[5].Controls.Add(ddlEdit);
TextBox tbox = e.Row.Cells[5].Controls[0] as Textbox;
if (tbox != null)
{
tBox.Visible = false;
}
}
}
How do I pass the data of DropDownList from OnRowDataBound to OnRowUpdating on DataRow? Below is my current code from OnRowUpdating:
GridViewRow gvr = gvResults.Rows[e.RowIndex];
DataRow drNew = dt.NewRow();
for(int i = 0l; i < Gvr.Cells.Count, i++)
{
drNew[i] = ((TextBox)gvr.Cells[i].Controls[0]).Text.Trim(); //Result is always the same like before for Cell[5], even though I slect the dropdown to "Test2" value.
}
I also tried to get the type of the type, it still returns a TextBox
gvr.Cells[i].Controls[0].GetType(); // When i = 5, which is I indicated on the first code snippet is DropDownList, returns TextBox

e.Row.Cells[5].Controls.Add(ddlEdit);
Here, you added your ddl to Controls collection and it will be the 2nd control in that list.
gvr.Cells[i].Controls[1].GetType();
should give you ddl that you want.

Related

How to get the value dynamically created checkbox value in asp.net gridview

I'm adding checkbox controls dynamically in asp.net gridview like this:
CheckBox cb1 = new CheckBox();
cb1.Text = row.Cells[3].Text;
row.Cells[3].Controls.Add(cb1);
And I want to access whether that checkbox is checked or not on button click event...
on button click I have tried this:
foreach (GridViewRow item in grdreport.Rows)
{
if (item.RowType == DataControlRowType.DataRow)
{
CheckBox checkbox1 = (CheckBox)item.FindControl("cb1");
// cb1.Checked = true;
if (checkbox1.Checked)
{
}
}
}
but it gives me an error:
Object reference not set to an instance of an object cb1 value is null
foreach (GridViewRow row in grdreport.Rows)
{
CheckBox checkbox1= (row.Cells[3].FindControl("cb1") as CheckBox);
if (checkbox1.Checked)
{
}
}
There is a need to access the checkbox trough a specific row and cell
Focus on this line:
CheckBox checkbox1 = (CheckBox)item.FindControl("cb1");
First check if item.FindControl("cb1") is giving you any value or not. More Info - Object Reference Exception
When checkbox or any object is added dynamically to Gridview during RowDataBound(), and if the value of that dynamic object should be retrieved on button click, enable view state for that object during RowDataBound() and it works like a charm.
CheckBox cb1 = new CheckBox();
cb1.Text = row.Cells[3].Text;
**cb1.EnableViewState = true;**
row.Cells[3].Controls.Add(cb1);

How to save option selected in Dropdownlist after selection

I am displaying columns in a GridView and one of the columns is a dropdownlist. I want to be able to save the option selected in the dropdownlist as soon as something is selected. I have done this with one of the columns that has a textbox so I was hoping to do something similar with the DropDownList.
The code for the textbox and dropdownlist:
protected void gvPieceDetails_ItemDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
JobPieceSerialNo SerNo = e.Row.DataItem as JobPieceSerialNo;
if (SerNo != null) {
TextBox txtComment = e.Row.FindControl("txtComment") as TextBox;
txtComment.Text = SerNo.Comment;
txtComment.Attributes.Add("onblur", "UpdateSerialComment(" + SerNo.ID.ToString() + ", this.value);");
DropDownList ddlReasons = (e.Row.FindControl("ddlReasons") as DropDownList);
DataSet dsReasons = DataUtils.GetUnapprovedReasons(Company.Current.CompanyID, "", true, "DBRIEF");
ddlReasons.DataSource = dsReasons;
ddlReasons.DataTextField = "Description";
ddlReasons.DataValueField = "Description";
ddlReasons.DataBind();
ddlReasons.Items.Insert(0, new ListItem("Reason"));
}
}
How to I create an update function for a dropdownlist?
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
string sel = ddlReasons.SelectedValue.ToString();
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; //can't find sel value
SerNo.Update();
}
Dropdownlist:
<asp:DropDownList ID="ddlReasons" runat="server" OnSelectedIndexChanged="DDLReasons_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
I created an OnSelectedIndexChanged function to get the selected value. But how do I then save that value? Is there a way to pass it into the UpdateSerialReason function?
Just move the string sel declaration outside the scope of DDLReasons_SelectedIndexChanged and get the Text of the SelectedItem since it's included in your data source.
private string sel;
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
sel = ddlReasons.SelectedItem.Text;
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; // Should now be available
SerNo.Update();
}
The way you had it previously it was only available in the local scope, i.e, inside the method in which it was being declared and used.
You can get selected value when you call your function:
UpdateSerialReason(/*Some SerNoID*/ 123456, ddlReasons.SelectedValue)
You will lose your value after postback is done if you save value to variable as Equalsk suggested. If you need to use your value on the other page you can save it in session.
If you are working within one asp.net page you can do as I suggested above. Then you can skip the postback on your DropDownList and call UpdateSerialReason when you need :)
And you might want to add property ViewStateMode="Enabled" and EnableViewState="true"

Hide DataList row based on value from web service

I am retrieving a set of value from a web service and populating a dataList with those values-
ActiveDataList.DataSource = ws.TermsReturnActive(sql);
ActiveDataList.DataBind();
How can I hide a particular column of the dataList depending on the value,
e.g.
if(value == 1)
{
//Hide Column
}
This action however would have to hide the same row of another dataList in parallel to it.
I can modify a cell on this second dataList using by retrieving the value from the first as so -
TextBox tb1 = (TextBox)sender;
DataListItem item1 = (DataListItem)tb1.NamingContainer;
TextBox txt1 = (TextBox)tData.Items[item1.ItemIndex].FindControl("tTextBox");
string term = txt1.Text;
So if I can retrieve a value from a separate dataList row, I was thinking I would also be able to adjust its visability.
How can I achieve this as the web service call is done in the page load so I believe it would have to be done when the dataList item is bound?
if iam right, you should have something like this in your aspx-file right?:
<asp:DataList ID="DataList1" runat="server" OnItemDataBound="DataList1_ItemDataBound"></asp:DataList>
As you can see you should add a "OnItemDataBound" Event where you can check your value and hide a item, if you want.
So you can react like this and hide some items:
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
TextBox tbCurrentTextBox = (TextBox)e.Item.FindControl("tTextBox");
if (DataList1.Items[e.Item.ItemIndex].ToString() == "1")
{
e.Item.Visible = false;
}
}
}

How to find a DropDownList in a GridView ItemTemplate without RowDataBound?

I have a DropDownList outside of a GridView and I have a DropDownList inside an ItemTemplate of a GridView. The DropDownList that is outside has a SelectedIndex_Changed event and when that fires, it should populate the DropDownList inside the GridView. The problem is that in the method that I use to populate the inside DropDownList, it can't find the control: Here is sample code that is called when the outside DropDownList is changed:
//Does not find ddlRoom
DropDownList ddlRoom = (DropDownList)gv.TemplateControl.FindControl("ddlRoom");
if (rows.Count() > 0)
{
var rooms = rows.CopyToDataTable();
ddlRoom.Items.Clear();
ddlRoom.Items.Add(new ListItem("Select...", "-1"));
ddlRoom.DataSource = rooms;
ddlRoom.DataBind();
}
I have also tried:
DropDownList ddlRoom = (DropDownList)gv.FindControl("ddlRoom");
You'll need to bound the dropdown for each row. Try something like this
DropDownList ddlRoom = null;
foreach(var gridRow in gv.Rows)
{
ddlRoom = gridRow.FindControl("ddlRoom") as DropDownList;
if (ddlRoom != null)
{
//your code here
}
}

Dropdownlist Selected value in postback

I have 2 dropdownlists(ddl1,ddl2) and a gridview with 2 dropdown lists(gddl1,gddl2). On SelectedIndexChanged event of ddl1 am changing SelectedIndex of gddl1 in postback.
My problem is
ddl1.databind() occurs at a button's click event. So once selectedindex of ddl1 changes, the selected value losts and returns back to initial value.
I cant use !IsPostback because am binding ddl1 on button click.
How can I retain ddl1 and ddl2 selected index.?
protected void btnProceed_Click(object sender, EventArgs e)
{
if(ddlLocation.SelectedIndex > -1) {
empDS = ws_service.GetEmpList(ddlLocation.SelectedValue, ((ddlDept.SelectedValue == "All") ? "" : ddlDept.SelectedValue), ((ddlGrade.SelectedValue == "All") ? "" : ddlGrade.SelectedValue));
appraiserDS = ws_service.GetAppList();
grdDetails.DataSource = empDS.Tables[ 0 ].DefaultView;
grdDetails.DataBind();
ddlAppraiserAll.DataSource = appraiserDS.Tables[ 0 ].DefaultView;
ddlAppraiserAll.DataTextField = "APPRAISER_NAME";
ddlAppraiserAll.DataValueField = "APPRAISER_ID";
ddlAppraiserAll.DataBind();
}
}
protected void ddlAppraiserAll_SelectedIndexChanged(object sender, EventArgs e)
{
foreach(GridViewRow gvRow in grdDetails.Rows) {
Control ctrl = gvRow.FindControl("ddlAppraiserId");
DropDownList ddl = ctrl as DropDownList;
if(ddl != null)
ddl.SelectedIndex = ddlAppraiserAll.SelectedIndex;
}
}
The issue here is synchronization and its where you get it and where you bind it, but you can also direct get the value using the Request.Form.
Request.Form[DropDownListID.UniqueID]
I'm not sure if i understood your problem since it's difficult to see what's ddl1, ddl2, gddl1 and so on and when each event is handled.
But my guess is:
DataBind your GridView in btnProceed_Click
Bind the two DropDownLists of the GridView only in RowDataBound
Then your "GridView-DropDownLists" are always up-to-date according to the selected value of ddl1
you can retain ddl1 and ddl2 selected index by storing them in viewstate as properties.
private string ddlSelectedIndex
{
set { ViewState["SelectedIndex"] = value; }
get { return ViewState["SelectedIndex"] == null ? string.Empty : ViewState["SelectedIndex"].ToString(); }
}
The above property is in string, you can create an int property in similar way or use the same and cast index as string. Your selected index will be retained on subsequent postbacks.

Categories

Resources