Positioning of DDL items? - asp.net

i have a dropDownList which gets its data from a database. Now after the data has bound, i programmatically add another listItem to the ddl, like so:
protected void ddlEffects_DataBound(object sender, EventArgs e)
{
DropDownList ddl = dwNewItem.FindControl("ddlEffects") as DropDownList;
ddl.Items.Add(new ListItem("","0")); //Adds an empty item so the user can select it and the item doesnt provide an effect
}
It all works, but the problem is that the newly added listItem appears at the bottom of the DDL. I want it to be the first item. I tried making the value 0, but its still at the bottom. Is there any way to put it at the top?
Thanks!

Check into the ddl.Items.Insert method that will allow you to insert items at a specific location.
Like this for example:
using (Entities db = new Entities())
{
ddlDocumentTypes.DataSource = (from q in db.zDocumentTypes where (q.Active == true) select q);
ddlDocumentTypes.DataValueField = "Code";
ddlDocumentTypes.DataTextField = "Description";
ddlDocumentTypes.DataBind();
ddlDocumentTypes.Items.Insert(0, "--Select--");
ddlDocumentTypes.Items[0].Value = "0";
}
Which using EF loads the DDL with items for the database, and then inserts at position zero a new item.

Related

ASP.Net GridView Edit/Update/Cancel/Delete Events On RowClick

We've got an ASP.Net application that contains a GridView Control that contains row edit functionality.
This allows a user to Edit, Delete, Or Cancel editing on a particular row.
For Example Read Only Mode Looks Like This:
And Edit Mode Looks Like this:
The mechanism that allows the user to enter Edit mode is based on an Edit Button in a template column that changes the selected row from a read only row to an editable row using a RowEditing event something like this:
protected void grdOfMine_RowEditing(object sender, GridViewEditEventArgs e)
{
grdOfMine.EditIndex = e.NewEditIndex;
ReBindDataGrid();
}
Canceling is pretty much the opposite where we have a button click event that changes the row back to ready only mode:
protected void grdOfMine_RowEditing(object sender, GridViewEditEventArgs e)
{
grdOfMine.EditIndex = -1;
ReBindDataGrid();
}
(Apologies to those who are already familiar with this aspect of ASP.Net forms development.)
We've also created a footer row that allows a user to add a new row:
We're looking for a way to extend the ASP.Net GridView control do this without using the buttons to fire the events.
For example:
Allow a user to enter edit mode for a row, by clicking in a cell of any given row and update the selected record say, on an Enter keyboard input event (Instead of the Edit Button).
Delete a record say, on a delete keyboard input event (Instead of the Delete Button).
Add a record in a similar fashion (Instead of the Add Button).
We were attempting this functionality using Infragistics controls, however we had a very tough time getting these to work, so we decided not to use them.
Thanks in advance
I am working on asp.net gridview on webforms and using Gridview RowCommand method of GridView OnRowCommand event for the Buttons View, Edit & Update inside TemplateField.
if (e.CommandName == "EditContract") {
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int SerialNo = (int)gvContract.DataKeys[row.RowIndex].Value;
int rowIndex = ((GridViewRow)((Button)e.CommandSource).NamingContainer).RowIndex;
gvContract.SelectRow(rowIndex);
using (SqlCommand cmd = new SqlCommand("spContractEdit", myObj.DbConnect()))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#RoleName", SqlDbType.Char).Value = Session["RoleName"];
cmd.Parameters.Add("#UnitName", SqlDbType.Char).Value = Session["UnitName"];
cmd.Parameters.Add("#ContrSerialNo", SqlDbType.Int).Value = SerialNo;
dAdapter = new SqlDataAdapter(cmd);
DataTable DtContract = new DataTable();
dAdapter.Fill(DtContract);
}
if (e.CommandName == "UpdateContract") {
lblMessage.Text = "";
lblFile.Text = "";
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int SerialNo = (int)gvContract.DataKeys[row.RowIndex].Value;
using (SqlCommand cmd = new SqlCommand("spContractUpdate", myObj.DbConnect()))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ContrNewRev", SqlDbType.VarChar).Value = ddNewOrRevised.SelectedValue;
cmd.Parameters.Add("#ContractTitle", SqlDbType.VarChar).Value = txtContractTitle.Text;
cmd.Parameters.Add("#FinancerID", SqlDbType.Int).Value = ddFinancer.SelectedValue;
}
This code is working fine when the page loads first time but has 2 problems after that. i.e. 1. It is editing and updating data when the page gets load for the first time but when I try to edit the same row or any other then it doesn't. I know it is because I have defined the !Page.IsPostback method on the Page_Load event but I do not know how to tackle this situation. 2. Problem is How to restrict the gridview row to update only that data whose row is selected?
Please suggest me a solution.
GridView Sample

How to bind data column to textbox?

I have datagridview and textboxes on form. I load records from different tables when user clicks any one radiobutton. Data in grid is shown perfectly. I want to show values of the row in those textboxes.
One solution can be: binding data from dataset.
Second one can be: transfer values of each cell of row to respective textbox.
Please help me. And, please tell me which one is better or is there any other method which is even better than these two.
Thanks in advance.
Try using a BindingSource
BindingSource bindingSource = new BindingSource();
DataSet dataSet = new DataSet();
DataAdapter da1 = new DataAdapter("Select * from Customers", conn1);
DataAdapter da2 = new DataAdapter("Select * form Orders", conn1);
da1.Fill(dataSet,"Customers");
da2.Fill(dataSet,"Orders");
//Let we set Customers table as bindiningSource datasource
bindingSource.DataSource = dataSet.Tables["Customers"];
private void RadioButtonCustomers_CheckedChanged(object sender, EventArgs e)
{
if(radioButtonCustomers.Checked==true)
bindingSource.DataSource =dataSet.Tables["Customers"];
}
private void RadioButtonOrders_CheckedChanged(object sender, EventArgs e)
{
if(radioButtonOrders.Checked==true)
bindingSource.DataSource = dataSet.Tables["Orders"];
}
//First param of Binding is to which prop of TextBox to bind the value
//Second param is the data source
//Third param is the data member or the column name of the table as datasource, so
//we have to get that table from casting the bindingSource datasource prop and casting it
//to DataTable obj and after that to take the ColumnName prop of the desired column
textBox1.DataBindings.Add(new Binding("Text",bindingSource,((DataTable)bindingSource.DataSource).Columns[0].ColumnName));
textBox2.DataBindings.Add(new Binding("Text",bindingSource,((DataTable)bindingSource.DataSource).Columns[1].ColumnName));
etc...
Even if you change the datasource prop of bindingSource, textboxes will remain binded to rowvalue of first and second column
Hope this help.
Sir I done it making a simple WindowsForm with 2 radio buttons, 2 textboxes and datagridview
here is the sln file http://www13.zippyshare.com/v/98590888/file.html this must help u.
I tried many options to display value in textbox on the same form, but it was not working as datagridview could display records of two different tables.
Instead, I used the following event of datagridview:
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
this.dataGridView1.SelectionChanged += new System.EventHandler(this.DisplayValueinTextBox);
}
In DisplayValueinTextBox, I wrote following code based on numbers of columns displayed for each table:
private void DisplayValueinTextBox(object sender, EventArgs e)
{
try
{
textBox1.Text = dataGridView1.SelectedCells[0].Value.ToString();
textBox2.Text = dataGridView1.SelectedCells[1].Value.ToString();
textBox3.Text = dataGridView1.SelectedCells[2].Value.ToString();
if (tblGrid == "Employee") //name of table which has more columns in grid
{
textBox4.Text = dataGridView1.SelectedCells[3].Value.ToString();
textBox5.Text = dataGridView1.SelectedCells[4].Value.ToString();
textBox6.Text = dataGridView1.SelectedCells[5].Value.ToString();
}
this.dataGridView1.SelectionChanged -= new System.EventHandler(this.DisplayValueinTextBox); //removed it as I was getting error.
}
catch (Exception exdisp)
{
MessageBox.Show(exdisp.Message);
}
}
I also changed SelectionMode property of dataGridView to FullRowSelect. This will ensure that textbox1 is displaying value of SelectedCells[0] even if user clicks any cell.
I still hope there is even a better option, so I wait for comments on this.

ASP.net Gridview Itemtemplate Dropdownlist

I am using C# ASP.net, and relative new to it, and need to accomplish below.
In my VS2010 web application project I have webform with a Gridview which fetches the data from a table.
In the Grid, I have Commandfiled Button (column1) and Item template with Dropdownlist (column2).
Use case is, user first selects one listitem from 3 list items (H, L and M) and then selects command button.
I am not able to figure out how to extract selected listitem from a selected row
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView2.SelectedRow;
Label4.Text = "You selected " + row.Cells[4].Text + ".";
Label5.Text = "You selected this list item from dropdownlist " + ???? ;
}
Thanks in advance.
The GridViewRow object provides the method FindControl (as do all container controls) to get access to a control in the row by its id. For example, if your DropDownList has an id of MyDropDown, you could use the following to access its selected value:
GridViewRow row = GridView2.SelectedRow;
DropDownList MyDropDown = row.FindControl("MyDropDown") as DropDownList;
string theValue = MyDropDown.SelectedValue;
// now do something with theValue
This is the recommended method for accessing all controls in your GridView. You want to avoid doing things like row.Cells[#] as much as possible, because it easily breaks when you re-arrange or add/remove columns from your GridView.

Dynamically update dropdownlist

I have this dropdownlist populated and everything. The only problem is that whenever I add a new item in the database through my website, the dropdownlist doesn't update for some reason.
private CurrentUser _cu = new CurrentUser();//just to check if use is an admin or not.
protected void Page_Load(object sender, EventArgs e)
{
_cu = (CurrentUser)Session[Common.SessVariables.CurUser];
if (!_cu.CanReport) { Response.Redirect("~/default.aspx"); }
CurrentUser cu = (CurrentUser)Session[Common.SessVariables.CurUser];
if (!IsPostBack)
{
foreach (PrefixAdd loc in cu.Prefix)//Prefix is a Property
{
ListItem x = new ListItem(loc.Prefix);
PrefixID.Items.Add(x);
}
}
}
#Wayne I'm using a store procedure to just insert a Prefix like Pre,yes,sey, etc. Then the list is populated with prefixes.
StringBuilder sbSQL = new StringBuilder(255);
sbSQL.Append(string.Format("exec insPrefix #Prefix=N'{0}';", PrefixBox.Text.Trim()));
string msg = string.Empty;
msg = (_oDAW.ExecuteNonQuery(sbSQL.ToString())) ? string.Format(Common.GetAppSetting(Common.ConfigKeys.User_Submit_Success),
PrefixBox.Text.Trim()) : Common.GetAppSetting(Common.ConfigKeys.SubmitFail); //this is a somewhat custom method for CS and databinding.
# Yuriy Rozhovetskiy Yea I add new items to this page with the dropdownlist.
Whenever you add an item to your database, you have to rebind your drop down list.
yourDropDown.DataSource = //...
yourDropDown.DataBind();
That is, DropDownLists (and other controls) have no way of knowing that their data has changed behind the scenes, they can't automatically detect it. You have to tell the controls to rebind their data manually.
Good job on the Page_Load(...){ if !(IsPostback) part.
Since you add new prefix on this page with some postback item you need to add this new item to PrefixID dropdown's Items collection and update the CurrentUser instance in Session right after you have add new prefix to database.

Making GridView Respond to 2 Drop Down Lists

I have got 2 DropDownLists on my Form and 1 GridView. I want the GridView to display the data according to the selection from the DropDownLists.
For Example, One DropDownList contains Names and another contains Dates. Both the DropDownLists can post back. So if I select a name from 1st DropDownList, the GridView should show all the results according to that Name. Similarly if i select the Date from the other DropDownList , the GridView should show the results according to the dates. But i cant figure out as how to bind GridView to respond to 2 DropDownList.
BTW i am binding both the Drop Down Lists and the Grid View to the DataSource Objects, which is getting data from the database.
Any Suggestions??
It's better and cleaner if You use two DataSource with selecting data from db, and binding each of them to the DropDownList. I tried in my ASP.NET app do what You want but unfortunatelly I have erorrs :/
My only sollution is to don't use DataSouce in aspx file, but in DropDownList SelectedItem event use DataContext and it's possible that then you could bind both to the same DataView like below. I am not sure, but maybe You must use null in DataSource to reset GridView before use new data source:
protected void btPokaz_Click(object sender, EventArgs e)
{
DataClassesDataContext db = new DataClassesDataContext();
var DzieciGrupa = from p in db.Dzieckos
where p.Grupy.Numer == Convert.ToInt32(this.dropListGrupy.SelectedValue)
orderby p.Nazwisko
select new { p.Imie, p.Nazwisko };
if (DzieciGrupa.Count() == 0) this.Label1.Text = "W " + this.dropListGrupy.SelectedValue.ToString() + " grupie nie ma dzieci zapisanych!";
this.GridGrupy.DataSource = null;
this.GridGrupy.DataSource = DzieciGrupa;
// this.GridView1.DataSourceID = String.Empty;
this.GridGrupy.DataBind();
Try it and tell say that works ;)
For Your problem You should create dwo EDM class for each data source. And simple in DDL select event Your choose of DataContext depends from user choose in DDL.
Example :
protected void DDL_SelectedItem(object sender, EventArgs e)
{
TypeOfQueryData query = null;//you must know what type is data You query
if(this.dropListGrupy.SelectedValue==someItemSelect)
{
DataClasses1DataContext db = new DataClasses1DataContext();
//query to get data from source
query= from p in db.Dzieckos
where p.Grupy.Numer == Convert.ToInt32(this.dropListGrupy.SelectedValue)
orderby p.Nazwisko
select new { p.Imie, p.Nazwisko };
}
if(this.dropListGrupy.SelectedValue==otherItemSelect)
{
DataClasses2DataContext db = new DataClasses2DataContext();
query= from p in db.Dzieckos
where p.Grupy.Numer == Convert.ToInt32(this.dropListGrupy.SelectedValue)
orderby p.Nazwisko
select new { p.Imie, p.Nazwisko };
}
this.GridGrupy.DataSource = null;
this.GridGrupy.DataSource = DzieciGrupa;
// this.GridView1.DataSourceID = String.Empty;//maybe You need do that
this.GridGrupy.DataBind();

Resources