I need edit the row of GridView in RowDataBound event.
If tried edit one row with field Area not null value I don't have problem, but if tried edit one row with field Area null or empty value I have the classic error :
Object reference not set to an instance of an object
On the line :
ddlCities.Items.FindByValue(hdnval.Value).Selected = true;
I think that inserted in my code this condition resolve the problem but without success :
if (!string.IsNullOrEmpty(hdnval.Value))
{
ddlCities.Items.FindByValue(hdnval.Value).Selected = true;
}
else
{
ddlCities.Items.FindByValue(hdnval.Value).Selected = false;
}
Please help me, thank you in advance.
My code below.
protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvProducts.EditIndex == e.Row.RowIndex)
{
DropDownList ddlCities = (DropDownList)e.Row.FindControl("Area");
HiddenField hdnval = (HiddenField)e.Row.FindControl("hdnArea");
string query = " Select distinct Area from ... ; ";
OdbcCommand cmd = new OdbcCommand(query);
ddlCities.DataSource = GetData(cmd);
ddlCities.DataTextField = "Area";
ddlCities.DataValueField = "Area";
ddlCities.DataBind();
if (!string.IsNullOrEmpty(hdnval.Value))
{
ddlCities.Items.FindByValue(hdnval.Value).Selected = true;
}
else
{
ddlCities.Items.FindByValue(hdnval.Value).Selected = false;
}
}
}
Please try :
if(ddlCities.Items.FindByValue(hdnval.Value) != null)
{
ddlCities.Items.FindByValue(hdnval.Value).Selected = true;
}
I hope I have helped you.
Related
There's a gridview in my program whose row's data is to be loaded in textboxes if edit is clicked.
Here is the code where I'm filling the data in textboxes after edit is clicked
protected void GV_Parameters_RowEditing(object sender, GridViewEditEventArgs e)
{
GV_Parameters.EditIndex = e.NewEditIndex;
int index = e.NewEditIndex;
IsEditing = true;
Label lbl_frmdate = (Label)GV_Parameters.Rows[index].FindControl("lbl_frmdate") as Label;
Label lbl_todate = (Label)GV_Parameters.Rows[index].FindControl("lbl_todate") as Label;
EditFromDate = lbl_frmdate.Text.ToUpper();
lbl_frm_edit.Text = EditFromDate;
EditToDate = lbl_todate.Text.ToUpper();
lbl_to_edit.Text = EditToDate;
Label lbl = (Label)GV_Parameters.Rows[index].Cells[3].FindControl("lbl_Is_holiday");
string is_holiday = lbl.Text;
Label lbl_std_intime = (Label)GV_Parameters.Rows[index].FindControl("lbl_std_intime") as Label;
Label lbl_std_outtime = (Label)GV_Parameters.Rows[index].FindControl("lbl_std_outtime") as Label;
string[] arr_std_intime;
string[] arr_std_outtime;
if (is_holiday != "1")//working day
{
r_work_holiday.SelectedIndex = 0;
IsHoliday = false;
if (lbl_std_intime.Text != "")
{
arr_std_intime = lbl_std_intime.Text.Split(':');
txt_std_TimeInHours.Text = arr_std_intime[0].ToString();
txt_std_TimeInMins.Text = arr_std_intime[1].ToString();
}
if (lbl_std_outtime.Text != "")
{
arr_std_outtime = lbl_std_outtime.Text.Split(':');
txt_std_TimeOutHours.Text = arr_std_outtime[0].ToString();
txt_std_TimeOutMins.Text = arr_std_outtime[1].ToString();
}
}
else
{
IsHoliday = true;
//r_workingday.Checked = false;
//r_holiday.Checked = true;
r_work_holiday.SelectedIndex = 1;
Label lbl_remarks = (Label)GV_Parameters.Rows[index].FindControl("lbl_remarks") as Label;
txt_holiday_desc.Text = lbl_remarks.Text;
}
collapse_state = "expand";
}
There is a radiobutton list who shows the edited row is holiday or working day,
if user changes the selection in radioButtonList, PostBack occurs and this is the time when all of the texboxes turn blank.
protected void r_work_holiday_SelectedIndexChanged(object sender, EventArgs e)
{
if(r_work_holiday.SelectedIndex==0)
{
IsHoliday = false;
}
else
{
IsHoliday = true;
}
collapse_state = "expand";
}
There's no any method in page load who is clearing the textboxes.
protected void Page_Load(object sender, EventArgs e)
{
if (IsEditing)
{
collapse_state = "expand";
}
if (!Page.IsPostBack)
{
BindYears();
}
}
Please help
Update ::
lbl_frm_edit and lbl_to_edit are not getting reset after postback.
The variable EditFromDate and EditToDate are being set by Viewstate
It's been sometime I worked in ASP controls but if I remember correctly, the content in textboxes are generally cleared on every post back by ASP .NET. The state of the textboxes are not saved.
Here is an answer I found while researching this issue.
You could store the value of the textboxes in ViewState and assign them back on the PageLoad event. Something like
txt_std_TimeOutHours.Text = arr_std_outtime[0].ToString();
txt_std_TimeOutMins.Text = arr_std_outtime[1].ToString();
ViewState["TimeOutHours"] = arr_std_outtime[0].ToString();
ViewState["TimeOutMins"] = arr_std_outtime[1].ToString();
And on the PageLoad event you can do this to restore the values.
if(Page.IsPostBack)
{
txt_std_TimeOutHours.Text = ViewState["TimeOutHours"].ToString();
txt_std_TimeOutMins.Text = ViewState["TimeOutMins"].ToString();
}
Hope this helps!
My code is like this : Now I have now idea how to get column name of selected row
protected void gv_imageslist_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string status;
string sts;
int result;
lblerror2.Text = "";
//((label)gv.Rows.FindControl("lbl1")).Text;
string str = gv_imageslist.c
if (str == "Status")
{
status = ((Label)gv_imageslist.Rows[e.RowIndex].FindControl("lbl_Status")).Text;
Gm.Gallery_Id = Convert.ToInt32(gv_imageslist.DataKeys[e.RowIndex].Value.ToString());
if (status == "True")
{
Gm.Is_Active = false;
}
else
{
Gm.Is_Active = true;
}
result = Gm.Change_Image_Status();
if (result == 1)
{
Build_ImageGalleryList();
}
else
{
lblerror2.Visible = true;
lblerror2.Text = "Unable to Change Status !";
}
}
else
//------For Checking of cover pic
{
sts = ((Label)gv_imageslist.Rows[e.RowIndex].FindControl("lbl_Cover")).Text;
Gm.Gallery_Id = Convert.ToInt32(gv_imageslist.DataKeys[e.RowIndex].Value.ToString());
string sp = ((Label)gv_imageslist.Rows[e.RowIndex].FindControl("lbl_category_Id")).Text;
Gm.Category_Id = Convert.ToInt32 (sp);
if (sts == "False")
{
Gm.Is_Cover = true;
}
else
{
Gm.Is_Cover = false;
}
result = Gm.Change_Gallery_Cover();
if (result == 1)
{
Build_ImageGalleryList();
}
else
{
lblerror2.Visible = true;
lblerror2.Text = "Unable To Change Cover Pic !!";
}
}
}
Try this code snippet;
gv.HeaderRow.Cells[i].Text
Why not create an object of the selected row and work with it from there?
i.e.
var selectedRow = (TYPE)gridViewName.GetFocusedRow();
You could then use the selectedRow object and call any properties belonging to it
i.e. var name = selectedRow.Name
It can be possible through DataKeyNames and Normal method also
1) 'e' as Commandargument
int index = Convert.ToInt32(e.CommandArgument);
string request = gvRequests.Rows[index].Cells[4].Text.ToString();
2) GridViewRow selectedRow = gvRequests.Rows[index];
string Id = gvRequests.DataKeys[index].Value.ToString().Trim();
string headerText=gvProductList.HeaderRow.Cells[1].Text;
protected void gvCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
LinkButton lnk = (LinkButton) e.Row.FindControl("lnk");
Label lblName= (Label) e.Row.FindControl("lblName");
lnk.Attributes.Add("onclick", "getValue(" + lblName.ClientID + ");"
}
}... You can try this... method in your own way
Enjoy... ..
Using VS 2010, C#, .NET 3.5
I have three User Defined Web Controls:
Control 1 has a ListBox and A Button
Control 2 has three Text-Boxes two DropDownLists and three Buttons
Control 3 has only a Table which is populated in code.
I have two pages:
Page 1 has Control 2 and Control 3
Page 2 has Control 1, Control 2, and Control 3
Functionality of Control 2 works perfectly on Page 1.
However, on Page 2 when the submit button is clicked, both DropDownLists ALWAYS show SelectedIndex = 0 and SelectedValue = "0".
All three Text Boxes and Buttons retain their value on both pages when the Submit Button on Control 2 is clicked. Only the DropDownLists fail to retain their value.
For reference, here is the code in the Submit Button OnClick event:
protected void btnSubmit_Click(object sender, EventArgs e)
{
clsLog.WriteLog("TrainingForm.ascx - Submit.");
tcCategoryError.Text = " ";
tcDateError.Text = " ";
tcDescriptionError.Text = " ";
tcHoursError.Text = " ";
tcMethodError.Text = " ";
foreach (Control c in this.Controls)
{
LogControls(c);
}
c_iTID = Convert.ToInt32(hTID.Value);
c_szUserName = hUserName.Value;
bool bValid = true;
DateTime dtTrainingDate = DateTime.MinValue;
string szTrainingDescription = "";
decimal dHours = 0M;
int iCategoryID = 0;
int iMethodID = 0;
if (!DateTime.TryParse(txtTrainingDate.Text, out dtTrainingDate))
{
bValid = false;
tcDateError.Text = "Please Enter Valid Training Date";
}
if (!decimal.TryParse(txtTrainingHours.Text, out dHours))
{
bValid = false;
tcHoursError.Text = "Please Enter Valid Training Hours";
}
if (this.ddlCategory.SelectedValue == "0")
{
bValid = false;
tcCategoryError.Text = "Please Select Training Category";
}
else
iCategoryID = Convert.ToInt32(this.ddlCategory.SelectedValue);
if (this.ddlTrainingMethod.SelectedValue == "0")
{
bValid = false;
tcMethodError.Text = "Please Select Training Method";
}
else
iMethodID = Convert.ToInt32(this.ddlTrainingMethod.SelectedValue);
if (txtTrainingDescription.Text.Trim() == "")
{
bValid = false;
tcDescriptionError.Text = "Please Enter Training description.";
}
else
szTrainingDescription = txtTrainingDescription.Text.Trim();
if (bValid)
{
clsData.UpdateTraining(c_iTID, "", c_szUserName, dtTrainingDate, szTrainingDescription, iCategoryID, dHours, iMethodID);
TrainingID = 0;
ClearForm();
}
OnEvent(new MyEventArgs(c_szUserName));
}
Code to populate DropDowns (part of the User Defined Control)
protected void BindddlCategory(int iCategoryID)
{
DataTable dt = clsData.GetTrainingCategories();
ddlCategory.Items.Clear();
ddlCategory.AppendDataBoundItems = true;
ddlCategory.Items.Add(new ListItem("Select Training Category", "0"));
ddlCategory.DataSource = dt;
ddlCategory.DataTextField = "TrainingCategory";
ddlCategory.DataValueField = "CID";
ddlCategory.DataBind();
if (iCategoryID != 0)
ddlCategory.SelectedValue = iCategoryID.ToString();
}
protected void BindddlCategory()
{
BindddlCategory(0);
}
protected void BindddlTrainingMethod(int iMethodID)
{
DataTable dt = clsData.GetTrainingMethods();
ddlTrainingMethod.Items.Clear();
ddlTrainingMethod.AppendDataBoundItems = true;
ddlTrainingMethod.Items.Add(new ListItem("Select Training Method", "0"));
ddlTrainingMethod.DataSource = dt;
ddlTrainingMethod.DataTextField = "TrainingCategory";
ddlTrainingMethod.DataValueField = "CID";
ddlTrainingMethod.DataBind();
if (iMethodID != 0)
ddlTrainingMethod.SelectedValue = iMethodID.ToString();
}
protected void BindddlTrainingMethod()
{
BindddlTrainingMethod(0);
}
FYI, the DDLs are NOT populated at Page load but implicitly populated when the event to show the form of the control is fired:
public void ShowTrainingEntry(int iTrainingID)
{
clsLog.WriteLog("TrainingForm.ascx - ShowTrainingEntry(" + iTrainingID.ToString() + ")");
hTID.Value = iTrainingID.ToString();
hUserName.Value = UserName;
int iCategoryID = 0;
int iMethodID = 0;
if (iTrainingID != 0)
{
DataTable dt = clsData.GetTrainingRecord(iTrainingID);
if (dt.Rows.Count == 1)
{
txtTrainingDate.Text = Convert.ToDateTime(dt.Rows[0]["TrainingDate"]).ToString("MM/dd/yyyy");
txtTrainingHours.Text = Convert.ToDecimal(dt.Rows[0]["Hours"]).ToString("N1");
txtTrainingDescription.Text = dt.Rows[0]["TrainingDescription"].ToString();
int.TryParse(dt.Rows[0]["CategoryCID"].ToString(), out iCategoryID);
int.TryParse(dt.Rows[0]["MethodCID"].ToString(), out iMethodID);
}
ShowChangeMessage(iCategoryID == 0 | iMethodID == 0);
ShowDeleteButton(true);
ShowCancelButton(true);
}
BindddlCategory(iCategoryID);
BindddlTrainingMethod(iMethodID);
tblMain.Visible = true;
}
Anyone have any ideas on why this is happening?
Thanks,
John
If you are adding the UserControls dynamically, you need to make sure they are added no later than Page_Init. This is so the controls are present when the page attempts to set the values from the PostBack.
I have this code in row data bound event :
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
string CCC = (string)DataBinder.Eval(e.Row.DataItem, "COLUMN");
DropDownList DropDownList1 = (DropDownList)e.Row.FindControl("DropDownList1");
}
How can I make the code to work in row updating event .
I want to add in rowupdating event only this code without the if condition.
string CCC = (string)DataBinder.Eval(e.Row.DataItem, "COLUMN");
DropDownList DropDownList1 = (DropDownList)e.Row.FindControl("DropDownList1");
Here by Iam showing the sample...for SQL Data Adapter Update...This also I learned from this StackOverFlow only.
private static void OnRowUpdating(object sender, SqlRowUpdatingEventArgs e)
{
string MyERowValu = e.Row["sl_no"].ToString().Trim();
if (e.Row["itm_description"].ToString().Trim().Length == 0)
{
//e.Status = UpdateStatus.SkipCurrentRow;
e.Status = UpdateStatus.SkipAllRemainingRows;
}
}
The Bleow Codes I used in Data_Save Areas...
SQLCon.Open();
blah...blah...blah...blah...
SqlTransaction Trans1 = MyItmDatas.WMSCon.BeginTransaction();
MyDataAdapter1.UpdateCommand.Transaction = Trans1;
MyDataAdapter1.InsertCommand.Transaction = Trans1;
MyDataAdapter1.RowUpdating += new SqlRowUpdatingEventHandler(OnRowUpdating);
MyDataAdapter1.RowUpdating += new SqlRowUpdatingEventHandler(OnRowUpdating);
myDataGrid1.CurrentCell = myDataGrid1.FirstDisplayedCell;
myDataGrid1.EndEdit();
try
{
MyDataAdapter1.Update(ItemTable);
Trans1.Commit();
MessageBox.Show(" ITEMS UPDATED TO ....... ITEM MASTER ", " ITEM MASTER UPDATE ");
}
catch (Exception ex)
{
if (Trans1 != null)
{
Trans1.Rollback();
}
MessageBox.Show(ex.Message, "Item Master Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
SQLCon.Close();
MyDataAdapter1.RowUpdating -= new SqlRowUpdatingEventHandler(OnRowUpdating);
myDataGrid1.Refresh();
I realy need help for this. I am using AjaxControlToolkit.TabContainer and using ASP.NET Framework 4.0. Gridview,textbox and button are placed in TabContainer on asp page. When I press button postback does happen but its not binding gridview to datatable and textbox contents are also not updated.
I debug the code and found when i press button postback does happen and content does fill up in gridview and textbox value also assigned with new value. but values doesnt display on the page. I dont know why its happening. please help.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ListBoxCustomer.Items.Count != 0)
{
int[] _selectedItems = ListBoxCustomer.GetSelectedIndices();
string _comma = "";
string _custID = "";
InitializeConnection();
if (_selectedItems.Length != 0)
{
foreach (int i in _selectedItems)
{
_custID = _custID + _comma + ListBoxCustomer.Items[i].Value;
_comma = ",";
}
if (custObj != null)
{
//DataTable _dt = new DataTable();
DataSet _ds = new DataSet();
GridViewCustomer.Visible = true;
GridViewCustomer.AutoGenerateColumns = true;
_ds = custObj.GetSelectedCustomers(1, _custID);
GridViewCustomer.DataSource = _ds.Tables[0];
GridViewCustomer.DataBind();
TextBoxTest.Text = GridViewCustomer.Rows.Count.ToString();
TextBoxTest.Text = "test";
}
}
}
}
}
thanks.
Perhaps the DataBind code is never being reached. Have you set some breakpoints to make sure the if-statements aren't blocking you? That is... Is ListBoxCustomer.Items.Count definitely not zero... Is custObj definitely not null?
Where do you assign a value to custObj?