Setting selected value to DropDownList in UserControl - asp.net

Could someone help me with setting the selected value of the DropDownList to the database given value. I have couple of TextBoxes for which it isn't hard to set the value from the database, but what drives me crazy is DropDownList.
<asp:TextBox ID="txtNaziv" runat="server" Width="430px" Text='<%# DataBinder.Eval(Container, "DataItem.Naziv") %>'></asp:TextBox>
As far as I know, it isn't possible to set the selected item value from the code front to the DropDownList, but I was able to find out something like this (code snippet from Telerik's RadGrid documentation):
protected void EmployeeDetails_DataBinding(object sender, System.EventArgs e)
{
ArrayList tocs = new ArrayList(new string[] { "Dr.", "Mr.", "Mrs.", "Ms." });
ddlTOC.DataSource = tocs;
ddlTOC.DataBind();
object tocValue = DataBinder.Eval(DataItem, "TitleOfCourtesy");
if (tocValue == DBNull.Value)
{
tocValue = "Mrs.";
}
ddlTOC.SelectedIndex = tocs.IndexOf((string)tocValue);
ddlTOC.DataSource = null;
}
The problem is I'm using Linq-to-SQL and I'm not sure how to recreate something like the above code. This is what I currently have:
protected void ddlTip_DataBinding(object sender, EventArgs e)
{
TSEntities db = new TSEntities();
var partType = (from pt in db.PartType
select new { pt.idPartType, pt.Naziv }).ToArray();
ddlTip.DataSource = partType;
ddlTip.DataTextField = "Naziv";
ddlTip.DataValueField = "idPartType";
ddlTip.DataBind();
object Tip = DataBinder.Eval(DataItem, "idPartType");
}
One more thing I have to add that this TextBoxes and DropDownList are inside the UserControl which is being used inside Telerik's RadGrid for its EditForm.
Any help would be appreciated.
Thank you!

You need to set the SelectedValue of the dropdown:
ddlTOC.SelectedValue = tocValue;
You can also do it like this:
ListItem li = ddlTOC.Items.FindByValue(tocValue);
if (li != null)
li.Selected = true;
EDIT:
Included code to bind list directly to db.PartType:
TSEntities db = new TSEntities();
ddlTip.DataSource = db.PartType;
ddlTip.DataTextField = "Naziv";
ddlTip.DataValueField = "idPartType";
ddlTip.DataBind();
ddlTip.SelectedValue = DataBinder.Eval(DataItem, "idPartType").ToString();

Try this one
ddlTip.Items.FindByValue(tocs).Selected = true;

Related

Why would formview disappear in Edit Mode

I know I must be missing something simple but I cannot find it so I will pose the question here. I have a formview with two templates (item and edititem).
The form is bound to the itemtemplate in the page_Load event and works fine. However, if is use !IsPostBack in the code-behind, the formview disappears when the edit button is clicked. If I remove the postback check from page_load, then the form view appears after the edit button is clicked.
The page does have viewstate enabled.
In general, what steps are needed to get the formview to transition between modes correctly?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
source = Session["Source"].ToString();
acctType = Session["AccountType"].ToString();
acctNumber = Convert.ToInt32(Session["AccountNumber"]);
if (source == "LifeLineDS")
{
ObjectDataSource fvObjDS = new ObjectDataSource();
fvObjDS.TypeName = "LifelineDataAccess.LifelineSubscriber";
fvObjDS.SelectMethod = "GetLifelineDSSubscriber";
fvObjDS.SelectParameters.Add(new Parameter("AcctType", TypeCode.String, acctType));
fvObjDS.SelectParameters.Add(new Parameter("AcctNumber", TypeCode.String, Session["AccountNumber"].ToString()));
fvObjDS.DataBind();
if (fvObjDS != null)
{
fvSubscriber.DataSource = fvObjDS; //subscriber.ToString();
fvSubscriber.DataBind();
initialProgramValue = (fvSubscriber.FindControl("txtEligibility") as TextBox).Text;
}
}
// more code for other sources...
}
protected void btnEdit_Click(object sender, EventArgs e)
{
fvSubscriber.ChangeMode(FormViewMode.Edit);
fvSubscriber.DataSource = Session["subscriber"]; //Adding this line resolved !IsPostBack problem
fvSubscriber.DataBind();
ObjectDataSource programsObjDS = new ObjectDataSource();
programsObjDS.TypeName = "LifelineDataAccess.LifelineSubscriber";
programsObjDS.SelectMethod = "GetPrograms";
DropDownList ddlEligibility = ((DropDownList)(fvSubscriber.FindControl("ddlEligibility")));
if (ddlEligibility != null)
{
ddlEligibility.DataSource = programsObjDS;
ddlEligibility.DataTextField = "ProgramName";
ddlEligibility.DataValueField = "ProgramName";
ddlEligibility.SelectedValue = initialProgramValue; // Set selected value to subscribers current program
ddlEligibility.DataBind();
}
}
This
fvSubscriber.ChangeMode(FormViewMode.Edit);
fvSubscriber.DataBind();
seems to not to set the data source. The rule is that either you have the DataSourceID set in the declarative part of your code (*.aspx, *.ascx) and the binding is done automatically upon each postback OR you bind programmatically which involves setting the data source and calling the DataBind().
My recommendation would be to move your ObjectDataSource to the declarative part of the code and set the DataSourceID on the FormView to the ID of the ObjectDataSource. This is clean and easy and the binding works always.

how to pass grid data in a gridview template textbox

I have a grid view name gvwsponsoor and it has 8 cells every cells has template textbox. if i am double click this textbox then open a model popup. i selected this popup data the data is show the textbox. but second rows are not show data, always data show first rows, how to pass all rows show data, please tell me solution any person .
i try to solved this code but not work in this code.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//foreach (GridViewRow grid in gvwSponsor.Rows)
//{
TextBox CostId = (TextBox)gvwSponsor.Rows[0].Cells[2].FindControl("txtCostCenter");
TextBox CostName = (TextBox)gvwSponsor.Rows[0].Cells[1].FindControl("txtDescription");
CostId = (TextBox)gvwSponsor.Rows[0].Cells[2].FindControl("txtCostCenter");
CostName = (TextBox)gvwSponsor.Rows[0].Cells[1].FindControl("txtDescription");
CostId.Text = GridView1.SelectedRow.Cells[2].Text;
CostName.Text = GridView1.SelectedRow.Cells[1].Text;
GridView1.SelectedIndex = -1;
DataTable dtaa = new DataTable();
dtaa = bll.GetNumber(CostId.Text);
if (dtaa.Rows.Count > 0)
{
GridView2.DataSource = dtaa;
GridView2.DataBind();
}
TextBox TxtOp = (TextBox)gvwSponsor.Rows[0].FindControl("txtOP");
TxtOp.Focus();
//}
}
You should process SelectedIndexChanged function of your gridview by using gvwSponsor.SelectedRow, not gvwSponsor.Rows[0]

How to get the selected row index and that selected row's cell value using delete button

I have use the templete field delete button in gridview, so when I click on any delete button in the gridview to delete a row at that time it will give the deleting row index with that selected row's cells[0] value. How can I do any one have a idea....?
protected void GridView3_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
int grdid = Int32.Parse(GridView3.Rows[index].Cells[0].Text);
IndiesProductDataContext ip = new IndiesProductDataContext();
ip.iLinks.DeleteAllOnSubmit(ip.iLinks.Where(c => c.ProductID == grdid));
ip.SubmitChanges();
}
I am using row command in gridview deleting row geting index but it does not work
You can set CommandArgument property of button
In Aspx:
<asp:Button ID="btnDeleteContact" CommandName="DeleteContact"
CommandArgument="<%# Eval("ContactID") %>" runat="server" >Delete</asp:Button>
In _RowCommand event of GridView:
If e.CommandName = "DeleteContact" Then
Dim objContacts As New CContacts
objContacts.ContactID = e.CommandArgument
objContacts.DomainID = Session("DomainID")
Dim strError As String = objContacts.DelContact()
End If
hope it helps
You can not do it in that way but you will have to use buttons click event to select the ID and then use that ID as perameter for second, different delete query.
i found The perfect solution of this problem...
protected void GridView3_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow gvr = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
int ci = Int32.Parse(GridView3.Rows[RowIndex].Cells[1].Text);
ProductDataContext ip = new ProductDataContext();
ip.iLinks.DeleteAllOnSubmit(ip.iLinks.Where(c => c.PID == ci));
ip.SubmitChanges();
}
this code worked properly in my module...

How to find control on GridView RowCommand Event?

i tried something like this but did not work:
GridViewRow row = (GridViewRow)(((Repeater)e.CommandSource).NamingContainer);
Repeater _rpt1 = row.Cells[8].FindControl("rptReg") as Repeater;
error:
Unable to cast object of type 'System.Web.UI.WebControls.Button' to type 'System.Web.UI.WebControls.Repeater'.
is there a way i can have the below code in OnRowCommand event using GridView?
actually i am trying to delete the row from the gridview control and when the user click on it and i am grabbing the mulitple ids and passing to SP and update the table and databind the gridview
GridViewRow row = gv.SelectedRow;
Repeater _rpt = gv.Rows[e.RowIndex].Cells[8].FindControl("rptReg") as Repeater;
Repeater _rpt1 = gv.Rows[e.RowIndex].Cells[9].FindControl("rptVisitor") as Repeater;
foreach (RepeaterItem item in _rpt.Items)
{
TextBox _txt = item.FindControl("txtId") as TextBox;
TextBox _txt1 = item.FindControl("txtName") as TextBox;
//update db
}
Please try this:
var viewRow = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
foreach (GridViewRow gvr in gvDetails.Rows)
{
var btnSelect = (ImageButton)viewRow.FindControl("btnSelect");
if (gvr == viewRow)
{
if (btnSelect.ImageUrl.ToLower() == "~/images/rbnormal.jpg")
{
btnSelect.ImageUrl = "~/Images/rbSelected.jpg";
btnSelect.Enabled = false;
}
}
else
{
btnSelect.ImageUrl = "~/Images/rbnormal.jpg";
btnSelect.Enabled = true;
}
}
Your error is telling me that the control named "rptReg" is a button.
The GridView has a property called DataKeys which can hold multiple IDs
So you would pull out the "PersonId" like:
string personId = GridView1.DataKeys[e.RowIndex]["PersonId"].ToString();

Getting Row's Name in a DataList

I have a datalist and would like to pull the row names from the table that I am getting my values from for the datalist. Heres an example of what I would like to do.
<HeaderTemplate>
'Get data row names
'Maybe something like Container.DataItem(row)?
</HeaderTemplate>
If you are using a DataTable as a Data Source for your Data List you could use the OnItemCreated method and provide a custom handler for the ItemCreated event to add the column header values. I'm not sure why you would want to do this. It sounds like a Repeater or GridView might be better suited to your needs. At any rate, here's the code.
<asp:DataList ID="DataList1" runat="server" OnItemCreated="DataList1_ItemCreated"
ShowHeader="true" >
<HeaderTemplate>
</HeaderTemplate>
</asp:DataList>
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString()))
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT [id], [name], [email], [street], [city] FROM [employee_tbl]", conn);
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(dt);
}
DataList1.DataSource = dt;
DataList1.DataBind();
}
protected void DataList1_ItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
foreach (DataColumn col in dt.Columns)
{
Literal lit = new Literal();
lit.Text = col.ColumnName;
e.Item.Controls.Add(lit);
}
}
}
You could do the following, but I doubt it would work. I don't believe DataItems are available at the point when the Header is being created.
((DataRowView)Container.DataItem).DataView.Table.Columns
If this works, you can loop through this collection and inspect each item's ColumnName property.
A better idea would be to either:
Create a property in codebehind that returns a List<string> of appropriate column headers. You can refer to this property in markup when you're declaring the header.
Add a handler for the ItemDataBound event and trap header creation. You will still need a way to refer to the data elements, which probably haven't been prepped at this point.

Resources