Saving dropdownlist value inside the repeater? - c#

I already retrieved my database(DescriptionCode) on dropdownlist inside on a repeater.
Now, I'm trying to save/add/insert on my database the selected value of dropdownlist but i
failed.
Any assistance gratefully received. Thanks!
protected void GeneralRepeater_OnItemDataBound(object sender,
RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList myDDL = (DropDownList)e.Item.FindControl("GeneralDDL");
Diagnosis oDiagnosis = new Diagnosis();
PlanOfCare oPlanOfCare = new PlanOfCare();
DataView dv = new DataView(oDiagnosis.GetDiagnosis());
myDDL.DataSource = PatientDiagnosis1;
myDDL.DataTextField = "DiagnosisCode";
myDDL.DataValueField = "DiagnosisCode";
myDDL.DataBind();
//PUT AN EMPTY FIELD FOR DROPDOWNLIST
ListItem LI = new ListItem("", "");
myDDL.Items.Insert(0, LI);
myDDL.SelectedValue = "0";
}
}
protected void cmdSave_Click(object sender, EventArgs e)
{
oPlanofCareSave.DiagnosesCode = //[1]this must the selected value of dropdownlist inside of repater
PlanSave(ooPlanofCareSave);
}

What about the cmdSave button, is that is inside the Repeater
You need to find out myDDL inside each row and for each of them you need to get this value.
foreach (RepeaterItem rptItem in RepeaterName.Rows)
{
DropDownList myDDL = (DropDownList)rptItem.FindControl("myDDL");
}

DropDownList myDDL = (DropDownList)GeneralRepeater.Items[indexvalue].FindControl("GeneralDDL");
oPlanofCareSave.DiagnosesCode = myDDL.SelectedValue;
it is easy to do it like that

Related

How to save changes from DropDownList to sql database?

I edited a DataGrid column so the location is now a DropDownList, which works fine. It populates the DropDownList from the database.
<asp:TemplateColumn HeaderText="Trailer Location">
<itemtemplate>
<asp:DropDownList ID="ddlTrailerLoc" runat="server" OnSelectedIndexChanged="ddlTrailerLoc_SelectedIndexChanged">
</asp:DropDownList>
<asp:HiddenField ID="hdlTrailerLoc" runat="server" Value='<%#Eval("TrailerLocation")%>' />
</itemtemplate>
</asp:TemplateColumn>
But when I change the value in the DropDownList I don't know how to save the changes made to the database.
protected void PopulateDDLs(DropDownList ddlTrailerLoc)
{
DataSet dsTrailerLocation = DataUtils.GetAllGenSmall(Company.Current.CompanyID, "Description", "", 1, false, "Description", false, "TrailerLocationNOCODE", 0);
if (dsTrailerLocation.Tables[0].Rows.Count > 0)
{
ddlTrailerLoc.DataSource = dsTrailerLocation;
ddlTrailerLoc.DataValueField = "Description";
ddlTrailerLoc.DataTextField = "Description";
ddlTrailerLoc.DataBind();
}
else
{
ddlTrailerLoc.Items.Insert(0, new ListItem("No Locations Entered", "0"));
}
}
protected void dgList_ItemCreated(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Header && e.Item.ItemType != ListItemType.Pager && e.Item.ItemType != ListItemType.Footer)
{
DropDownList ddlTrailerLocation = e.Item.FindControl("ddlTrailerLoc") as DropDownList;
if (ddlTrailerLocation != null)
{
PopulateDDLs(ddlTrailerLocation);
//set the value in dropdown
HiddenField hdlTrailerLoc = e.Item.FindControl("hdlTrailerLoc") as HiddenField;
if (hdlTrailerLoc != null)
{
ddlTrailerLocation.SelectedValue = hdlTrailerLoc.Value;
}
}
}
}
I tried creating this ddlTrailerLoc_SelectedIndexChanged method but the event doesn't run.
protected void ddlTrailerLoc_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList list = (DropDownList)sender;
TableCell cell = list.Parent as TableCell;
DataGridItem item = cell.Parent as DataGridItem;
int selectedIndex = item.ItemIndex;
string selectedItem = item.Cells[0].Text;
// now save your work here and rebind the grid.
Trailer.UpdateTrailer(int.Parse(TrailerID), Company.Current.CompanyID,
txtTrailerReg.Text,
ddlTrailerLocation.Text);
ddlTrailerLocation.DataValueField = "Description";
ddlTrailerLocation.DataTextField = "Description";
ddlTrailerLocation.DataBind();
}
Please add AutoPostBack="True" in dropdown. It will work
<asp:DropDownList ID="ddlTrailerLoc" runat="server" OnSelectedIndexChanged="ddlTrailerLoc_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList>
Please write code as below
protected void ddlTrailerLoc_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlTrailerLoc=sender as DropDownList;
if(ddlTrailerLoc!=null)
{
int trailerId=int.Parse(ddlTrailerLoc.SelectedValue.ToString());
//Save selected value in Database
// now save your work here and rebind the grid.
Trailer.UpdateTrailer(trailerId, Company.Current.CompanyID,
txtTrailerReg.Text,
ddlTrailerLoc.Text);
ddlTrailerLocation.DataValueField = "Description";
ddlTrailerLocation.DataTextField = "Description";
ddlTrailerLocation.DataBind();
}
}

How to edit databound combobox in c#

In my winForm application I have added databound combobox column in a datagridview. User needs to be able to select an item from dropdown list or write in the combobox. But it wouldn't let me write in the combobox as datasource is set. This is my code:
var entityModel= new AdminEntities();
var filterPractice = (from b in entityModel.FILTER where b.PRACTICE != null select b.PRACTICE).Distinct().OrderBy(y => y);
dgvCboColumn(filterPractice, "PRACTICE");
private void dgvCboColumn(dynamic item, string colName)
{
int i = dgvLoadTable.Columns[colName].Index;
DataGridViewComboBoxColumn dgvCol = new DataGridViewComboBoxColumn();
dgvCol.DataSource=item;
dgvCol.DataPropertyName = colName;
dgvLoadTable.Columns.Insert(i, dgvCol);
dgvLoadTable.Columns[i].HeaderText = dgvLoadTable.Columns[i + 1].HeaderText;
dgvLoadTable.Columns[i + 1].Visible = false;
dgvLoadTable.Columns.RemoveAt(i + 1);
}
private void HandleEditShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
var cbo = e.Control as ComboBox;
if (cbo == null)
{
return;
}
cbo.DropDownStyle = ComboBoxStyle.DropDown;
cbo.Validating -= HandleComboBoxValidating;
cbo.Validating += HandleComboBoxValidating;
}
private void HandleComboBoxValidating(object sender, CancelEventArgs e)
{
var combo = sender as DataGridViewComboBoxEditingControl;
if (combo == null)
{
return;
}
if (!combo.Items.Contains(combo.Text))
{
var comboColumn = this.dgvLoadTable.Columns[this.dgvLoadTable.CurrentCell.ColumnIndex] as DataGridViewComboBoxColumn;
combo.Items.Add(combo.Text);
comboColumn.Items.Add(combo.Text);
this.dgvLoadTable.CurrentCell.Value = combo.Text;
}
}
Can anyone tell me how can I make the combobox editable, please?
you can manually get the items frm datasource using Oledb or Ado recordset nd fill de comboBox manually by using for loops.. so basically you can also edit the items..

Accessing dynamically generated dropdownlist in Gridview_RowUpdating event

I am using Gridview with AutoGenerateColumns="True", so gridview columns are generated dynamically. Now in case of edit, I am adding dropdownlist dynamically for one of the field in the gridview. Please see following code:
protected void grdViewConfig_RowEditing(object sender, GridViewEditEventArgs e)
{
grdViewConfig.EditIndex = e.NewEditIndex;
BindGridView();
clientBAL = new TMIWsBALClient();
var lstAppIds = clientBAL.GetDistinctApplicationIds();
GridViewRow grdRow = grdViewConfig.Rows[e.NewEditIndex];
for (int i = 0; i < grdRow.Cells.Count; i++)
{
if (grdRow.Cells[i].GetType().Equals(typeof(DataControlFieldCell)))
{
DataControlFieldCell dcField = (DataControlFieldCell )grdRow.Cells[i];
if (dcField.ContainingField.HeaderText.ToLower().Equals("applicationid"))
{
DropDownList drpDwnAppIds = new DropDownList();
drpDwnAppIds.ID = "drpDwnAppIds";
drpDwnAppIds.DataSource = lstAppIds;
drpDwnAppIds.DataBind();
var tb = dcField.GetAllControlsOfType<TextBox>(); ;// grdRow.Cells[i].GetAllControlsOfType<TextBox>();
TextBox firstTb = (TextBox)tb.First();
foreach (ListItem lstItem in drpDwnAppIds.Items)
{
if (firstTb.Text.Equals(lstItem.Text, StringComparison.CurrentCultureIgnoreCase))
{
lstItem.Selected = true;
}
}
dcField.Controls.Remove(firstTb);
dcField.Controls.Add(drpDwnAppIds);
}
}
}
}
Now in Gridview_RowUpdating event, I am trying to fetch the dropdownlist in similar way, but I am unable to get it. GetAllControlsOfType() is an extension method, which will return all the child controls under selected parent. In this case, parent is gridview cell and child control is dropdownlist. But it is returning null.
protected void grdViewConfig_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
strTableName = txtTable.Text.Trim();
string strAppId;
GridViewRow grdRow = grdViewConfig.Rows[grdViewConfig.EditIndex];
for (int i = 0; i < grdRow.Cells.Count; i++)
{
if (grdRow.Cells[i].GetType().Equals(typeof(DataControlFieldCell)))
{
DataControlFieldCell dcField = (DataControlFieldCell)grdRow.Cells[i];
if (dcField.ContainingField.HeaderText.ToLower().Equals("applicationid"))
{
var drpDwn = dcField.GetAllControlsOfType<DropDownList>();
DropDownList drpDwnAppIds = (DropDownList)drpDwn.First();
strAppId = drpDwnAppIds.SelectedValue;
}
}
}
}
What am I missing? Please help. Also let me know if more information is needed.
Thank you in advance.
Dynamically generated controls need to be recreated on every postback. In your case the DropDownList controls you created no longer exist when you hit the grdViewConfig_RowUpdating handler.
Generally in this sort of case you would set AutoGenerateColumns to false and manually define your columns which would allow you to define a TemplateField which contains an ItemTemplate for read only mode and an EditItemTemplate for edit mode which could then contain your DropDownList.

ASP.Net Gridview not rebind data on button click

i am new in asp.net i using LINQ with asp.net on button click event my gridview not rebind data and yes gridview is into the updatepanel
'>
'>
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gvClientData.Rows)
{
if (((CheckBox)gvr.FindControl("chkdisplay")).Checked == true)
{
string Index = ((Label)gvr.FindControl("lblIndex")).Text;
int GIIndex = Convert.ToInt32(Index);
GI_InsureMaster insertclientinfo = vjdb.GI_InsureMasters.Single(upd => upd.GIMastIndex == GIIndex);
insertclientinfo.SendToCompany = true;
vjdb.SubmitChanges();
}
}
BindAgencyData();
Response.Redirect(Request.RawUrl);
}
It seems you are trying to modify an object and then saving it back to the DB, but you are doing it wrong.
You are querying the object from a different Data Context, vjdb and you are calling SubmitChanges on linqobject. You should call SubmitChanges on vjdb
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gvClientData.Rows)
{
if (((CheckBox)gvr.FindControl("chkdisplay")).Checked == true)
{
string Index = ((Label)gvr.FindControl("lblIndex")).Text;
int GIIndex = Convert.ToInt32(Index);
GI_InsureMaster insertclientinfo = vjdb.GI_InsureMasters.Single(upd => upd.GIMastIndex == GIIndex);
insertclientinfo.SendToCompany = true;
vjdb.SubmitChanges(); //HERE
}
}
BindAgencyData();
Response.Redirect(Request.RawUrl);
}
Assuming that BindAgencyData is querying database for latest/updated record and then binding the data to the grid.

RowCommand not getting fired on Dynamically created GridView

I am creating a gridview dynamically with a ButtonField and several BoundFields. ButtonField button type is LinkButton. If i run it the buttonclick triggers a post back but rowCommand is not triggered. It is not triggered even if i use AutogenerateSelectButton. The event is dyanamically bound. Code As follows:
protected void B_Search_Click(object sender, EventArgs e) //Search buttonclick that creates and displays the gridview
{
gd = getGridView(); //defines the gridview with columns and buttonfield
gd.DataSource = executeAdvanceSearch(); //retrieves data from DB as Dataset
gd.DataBind();
gd.RowCommand += new GridViewCommandEventHandler(gdView_RowCommand); //Rowcommand event binding
PlaceHolder1.Controls.Add(gd);
}
protected void gdView_RowCommand(object sender, GridViewCommandEventArgs e) //not getting triggered on postback
{
int index = Convert.ToInt32(e.CommandArgument);
GridView gdView = (GridView)sender;
if (e.CommandName == "IDClick")
{
//Do something
}
}
private GridView getGridView()
{
GridView gdView = new GridView();
gdView.AutoGenerateColumns = false;
gdView.AutoGenerateSelectButton = true;
string name;
string[] field = ZGP.BLL.Search.getResultFormat(Convert.ToInt32(DDL_ResultView.SelectedValue), out name); //Ignore. This jst gets columnNames
if (field.Count() != 0)
{
gdView.Columns.Add(getSelectButton()); //Adds linkbutton
foreach (string cName in field) //ignore. This adds columns.
if (!String.IsNullOrEmpty(cName))
{
gdView.Columns.Add(GV_DataColumn.getGridViewColumn((DataColumnName)Enum.Parse(typeof(DataColumnName), cName))); //Ignore. adds columns
}
}
return gdView;
}
private ButtonField getSelectButton()
{
ButtonField _bf = new ButtonField();
_bf.ButtonType = ButtonType.Link;
_bf.HeaderText = "ID";
_bf.DataTextField = "ID";
_bf.CommandName = "IDClick";
return _bf;
}
Thanks for the help.
if (e.CommandName=="CommandName")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
string boundFieldText= row.Cells[0].Text;
}
You'll need to create the grid view on each postback.

Categories