DropdownList SelectedValue property doesn't accept value during edit operation - c#

I have a cascading dropdownlist inside a gridview which contains 5 columns which are ItemsType, ItemList, UnitPrice, Quantity and Total. Selecting ItemsType in 1st dropdownlist will populate items in 2nd dropdownlist i.e. ItemList which is bound to database.
Problem that I am getting is that when I click Edit button, items in 2nd dropdownlist Itemstype isn't selected though I have assigned the selectedValue.
When I ran the webform in debugging mode I saw that though value has been rightly assigned to dropdownlist.selectedvalue, it isn't accepting the value at all.
The weird thing is that when I click the edit button for the second time after 1st debug, items in dropdownlist are selected correctly.
I have used the following
ddlCarriedItems.SelectedValue = SValue;
Though SValue has values of itemlist, SelectedValue displays none.
Here's the code.
protected void btnEdit_Click(object sender, EventArgs e)
{
try
{
Button btn = (Button)sender;
GridViewRow gv = (GridViewRow)btn.NamingContainer;
string VRM_id = gv.Cells[0].Text;
dc.Company_code = Convert.ToInt32(Session["company_code"].ToString());
dc.Vrm_id = Convert.ToInt32(VRM_id);
DataTable dtVRM_CP = vrmbll.edit_VRM_carried_products(dc);
int rowIndex = 0;
if (dtVRM_CP.Rows.Count > 0)
{
for (int i = 0; i < dtVRM_CP.Rows.Count; i++)
{
DropDownList ddlItemsType = (DropDownList)gvCarriedItems.Rows[rowIndex].Cells[1].FindControl("ddlItemsType");
DropDownList ddlCarriedItems = (DropDownList)gvCarriedItems.Rows[rowIndex].Cells[2].FindControl("ddlCarriedItems");
TextBox txtItemPrice = (TextBox)gvCarriedItems.Rows[rowIndex].Cells[3].FindControl("txtItemPrice");
TextBox txtItemQty = (TextBox)gvCarriedItems.Rows[rowIndex].Cells[4].FindControl("txtItemQty");
TextBox txtItemTotal = (TextBox)gvCarriedItems.Rows[rowIndex].Cells[5].FindControl("txtItemTotal");
ddlItemsType.SelectedIndex = Convert.ToInt32((dtVRM_CP.Rows[i]["items_type"]).ToString());
int itemstype = ddlItemsType.SelectedIndex;
string SValue = dtVRM_CP.Rows[i]["items"].ToString();
if (itemstype == 1)
{
ddlCarriedItems.SelectedValue =SValue;
}
else if (itemstype == 2)
{
ddlCarriedItems.SelectedValue = SValue;
}
else if (itemstype == 3)
{
ddlCarriedItems.SelectedValue = SValue;
}
else
{ }
txtItemPrice.Text = dtVRM_CP.Rows[i]["items_price"].ToString();
txtItemQty.Text = dtVRM_CP.Rows[i]["items_qty"].ToString();
txtItemTotal.Text = dtVRM_CP.Rows[i]["items_total"].ToString();
if (i != (dtVRM_CP.Rows.Count) - 1 && gvCarriedItems.Rows.Count != (dtVRM_CP.Rows.Count))
{
AddNewRow();
}
rowIndex++;
}
}
}
catch
{ }
}

Ok I've found the problem in my code. The thing is that I had to bind dropdownlist everytime before assigning value to ddlCarriedItems.SelectedValue.
I modified my code as following as per #king.code suggestion:
if (itemstype == 1)
{
DataTable dt = vrmbll.select_raw_materials_production(dc);
ddlCarriedItems.DataSource = dt;
ddlCarriedItems.DataValueField = "ID";
ddlCarriedItems.DataTextField = "Name";
ddlCarriedItems.DataBind();
ddlCarriedItems.Items.Insert(0, new ListItem("----- Select -----", "-1"));
ddlCarriedItems.SelectedValue = SValue;
}
But I have no idea why the previous code worked when I ran debugging for 2nd time.

Related

Copy multiple selected rows from datagridview to textboxes

I have a datagridview named PTable which shows a table from database. I also have a button that functions to copy the data from selected rows to the textboxes I have.
This code that I have right now copies two selected rows from the datagridview but when I only select one row or when I select more than 2 rows, it says that "Index was out of range"
What should happen is that it should copy any number of rows and not only 2 rows
private void button11_Click(object sender, EventArgs e)
{
productid.Text = PTable.SelectedRows[0].Cells[0].Value + string.Empty;
productname.Text = PTable.SelectedRows[0].Cells[1].Value + string.Empty;
unitprice.Text = PTable.SelectedRows[0].Cells[4].Value + string.Empty;
productid2.Text = PTable.SelectedRows[1].Cells[0].Value + string.Empty;
productname2.Text = PTable.SelectedRows[1].Cells[1].Value + string.Empty;
unitprice2.Text = PTable.SelectedRows[1].Cells[4].Value + string.Empty;
}
If a user have not selected two rows, your index 1 (PTable.SelectedRows[1]) is not valid, because the item is not there.
Before you can run this code, you have to check, if the user selected two rows:
if (PTable.SelectedRows.Count == 2)
{
//Your code ...
}
else
{
//Not two rows selected
}
First, make sure SelectionMode of DataGridView to FullRowSelect(Hope you have done it already)
Second, Use foreach or any looping logic to go through each selected rows.
Third, It's always better to write modular code. Write a validation method which returns TRUE or FALSE based on selection of the grid rows.
Now based on returned value you need to continue writing your business logic.
Fourth, Make sure to use NULL checks
So let's start by re-factoring the code.
private void button11_Click(object sender, EventArgs e)
{
If(IsRowOrCellSelected())
{
//loop through selected rows and pick your values.
}
}
I am just writing sample, make sure PTable is accessible.
private boolean IsRowOrCellSelected()
{
if (PTable.SelectedRows.Count > 0)
{
DataGridViewRow currentRow = PTable.SelectedRows[0];
if (currentRow.Cells.Count > 0)
{
bool rowIsEmpty = true;
foreach(DataGridViewCell cell in currentRow.Cells)
{
if(cell.Value != null)
{
rowIsEmpty = false;
break;
}
}
}
if(rowIsEmpty)
return false;
else
return true;
}
Code can be still improved.
To work with varying number of selected rows I suggest the following.
My approach is:
There may be more than 5 rows, that You have to display. First create 3 panels for the TextBoxes. I have named the one for the productids as here. Generate the textboxes from code, this way it's easier to maintain more than 5 selected rows:
// This code goes to the constructor of the class. Not in the button click
List<TextBox> productids = new List<TextBox>();
List<TextBox> productnames = new List<TextBox>();
List<TextBox> unitprices = new List<TextBox>();
for (int i = 0; i < 5; i++)
{
productids.Add(new TextBox { Top = i * 32 });
productnames.Add(new TextBox { Top = i * 32 });
unitprices.Add(new TextBox { Top = i * 32 });
here.Controls.Add(productids[i]);
here2.Controls.Add(productnames[i]);
here3.Controls.Add(unitprices[i]);
}
Than You can in the button click set the value for each selected row:
// This code goes to the button click
// first empty the Textboxes:
foreach (TextBox productid in productids)
{
productid.Text = string.Empty;
}
foreach (TextBox productname in productnames)
{
productname.Text = string.Empty;
}
foreach (TextBox unitprice in unitprices)
{
unitprice.Text = string.Empty;
}
for (int i = 0; i < PTable.SelectedRows.Count; i++)
{
productids[i].Text = PTable.SelectedRows[i].Cells[0].Value.ToString();
productnames[i].Text = PTable.SelectedRows[i].Cells[1].Value.ToString();
// or better... Name the columns
// unitprices[i].Text = PTable.SelectedRows[i].Cells["unitPrices"].Value.ToString();
unitprices[i].Text = PTable.SelectedRows[i].Cells[4].Value.ToString();
}

Grid View check the value is exist?

I have a drop down list "ddlMitchelLandscape2" ,when add button triggers ,i add the selected item value in to gridview.
I am stuck here ,how to check the gridview, before add the value to grid view. The selected item is already exist in grid view or not when the add button is triggered .
Some one help me how to check the value is exist in gridview before add it to gird view please ?
protected void btnAddMitchellLandscape_Click(object sender, EventArgs e)
{
//validate to make sure Mitchell Landscape is entered
if (!ValidateMitchellPage())
return;
Assessment objAssessment = (Assessment)Session[Session_CurrentAssessment];
if (ddlMitchelLandscape2.GetSelectedItemValue > 0)
{
if (lblMitchellID.Text == string.Empty)
{
//add
AssessmentEntity objAssessmentEntity = new AssessmentEntity();
Assessment.tblMitchellLandscapeIDRow row =
objAssessment.tblMitchellLandscapeID.NewtblMitchellLandscapeIDRow();
row.MitchellLandscapeID = ddlMitchelLandscape2.GetSelectedItemValue;
row.MitchellLandscapeName = ddlMitchelLandscape2.GetSelectedItemText;
}
else
{
//Add button not visible when its not a new row
ctrlHeader.ShowError("Error: Unknown error");
return;
}
//refresh data bound table
PopulateMitchellDetailsToForm(ref objAssessment);
//clear after save
btnClearMitchellLandscape_Click(null, null);
}
}
ValidateMitchellPage()
private bool ValidateMitchellPage()
{
litMitchellError.Text = string.Empty;
if (ddlMitchelLandscape2.GetSelectedItemValue <= 0)
litMitchellError.Text = "Please select Mitchell Landscape";
if (litMitchellError.Text.Trim() == string.Empty)
{
litMitchellError.Visible = false;
return true;
}
litMitchellError.Visible = true;
return false;
}
DataBind to grid view
private void PopulateMitchellDetailsToForm(ref Assessment objAssessment)
{
Assessment.tblMitchellLandscapeIDRow[] MlData
= (Assessment.tblMitchellLandscapeIDRow[])objAssessment.tblMitchellLandscapeID.Select("SaveType <> " + Convert.ToString((int)EnumCollection.SaveType.RemoveOnly));
this.gvMitchellLandscape.DataSource = MlData;
this.gvMitchellLandscape.DataBind();
}
You have to check the selected value from the dropdown or combobox in gridview by checking each row.
You can use following code to get row of gridview.
bool isValueExist=False;
for (int i = 0; i < gridview.Rows.Count; i++)
{
String val = gridview.Rows[i].Cells[0].Value.ToString();
if(val == your_drop_down_value)
{
isValueExist=True;
break;
}
}
You have to change the cell number according to your gridview design.

GridView and RowDataBound event

I can edit single row in the GridView.
But when in MySQL database the value of field "card" is not null I need stopping the edit in this single row of GridView (and passed the row in closed state).
I tried this solution, but in GridView I've all rows of GridView in "closed state" even when the value of field "card" is null, why?
The condition is inserted in RowDataBound event, it's correct?
My code below.
I would greatly appreciate any help you can give me in working this problem.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var obj = ((DataRowView)e.Row.DataItem)["card"];
ImageButton edit = (ImageButton)e.Row.FindControl("imgbtnEdit");
if (obj != null)
{
edit.Enabled = false;
edit.ToolTip = "Closed state";
}
}
if (e.Row.RowType == DataControlRowType.Pager)
{
DropDownList ddl = (DropDownList)(e.Row.FindControl("ddlpages"));
Label lblPageCount = (Label)e.Row.FindControl("lblPageCount");
if (lblPageCount != null)
lblPageCount.Text = GridView1.PageCount.ToString();
for (int i = 1; i <= GridView1.PageCount; i++)
{
ddl.Items.Add(i.ToString());
}
ddl.SelectedIndex = GridView1.PageIndex;
if (GridView1.PageIndex == 0)
{
((ImageButton)e.Row.FindControl("ImageButton1")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton2")).Visible = false;
}
if (GridView1.PageIndex + 1 == GridView1.PageCount)
{
((ImageButton)e.Row.FindControl("ImageButton3")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton4")).Visible = false;
}
}
}
This is because DBNull.Value and null are two different things.
var obj = ((DataRowView)e.Row.DataItem)["card"];
if (!DBNull.Value.Equals(obj))
{
edit.Enabled = false;
edit.ToolTip = "Closed state";
}
This will check to see if the "card" value is a null database value, rather than a null object.

create a dropdonlist and add item on onload function

I have created a dropdown list. I have added item to dropdown list on onload function.
protected void Page_Load(object sender, EventArgs e)
{
int x = DateTime.Now.Year;
List<string> str = new List<string>();
for (int i = x; i >= 1975; i--)
{
str.Add(i.ToString());
}
ddlYear.DataSource = str;
ddlYear.DataBind();
}
But when I click on button to submit the selected value of dropdownlist to database it always goes 2013 in my database. ddlYear is my dropdownlist id.
When you click the submit button page makes postback. Because of this reason dropdownlist selected value 2013. Change your code like this.
if (!Page.IsPostBack)
{
int x = DateTime.Now.Year;
List<string> str = new List<string>();
for (int i = x; i >= 1975; i--)
{
str.Add(i.ToString());
}
ddlYear.DataSource = str;
ddlYear.DataBind();
}
it is not clear what you are submitting to the database:
Try submitting ddlyear.SelectedItem.Value to the database.

bind many dropdownlist in a continous fashion

Hi all i need to bind a list of dropdown to values in database.Each drop down will be inside a panel and i have named it as ddlxx1,ddlxx2,ddlxx3 in a continuous fashion. all these drop down list will have the same data source.Is there any way to bind these control in a loop or should i find control each time which is in panel then bind it?
Something like:
for(int i=1;i<=10;i++)
{
ddlxx+"i".DataSource = Prod.GetValues();
ddlxx+"i".DataTextField = "ComponentID";
ddlxx+"i".DataValueField = "ComponentName";
ddlxx+"i".DataBind();
}
Please help
If your drop down lists are added to the mark-up you can simply do the following:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
for(int i=1;i<=10;i++)
{
var ddl = FindControl("ddlxx" + i) as DropDownList;
if (ddl != null)
{
BindDropDown(ddl);
}
}
}
}
private void BindDropDown(DropDownDataList ddl)
{
ddl.DataSource = Prod.GetValues();
ddl.DataTextField = "ComponentID";
ddl.DataValueField = "ComponentName";
ddl.DataBind();
}
Try this:
for (int i = 1; i <= 10; i++)
{
DropDownList drp = (DropDownList)panel1.FindControl("ddlxx" + i.ToString());//panel1 is your panel which contain dropdown ddlxx1,ddlxx2,ddlxx3...
drp.DataSource = Prod.GetComponents();
drp.DataTextField = "ComponentID";
drp.DataValueField = "ComponentName";
drp.DataBind();
}

Categories