populating DropDownList in a gridview with array elements - c#

I have been trying to Populate a DropDownList in my gridview with array elements . The array consists of the column names from another gridview .The array element seems to get the column names from its source but i can not figure out how to give that to the dropdownlist.Here is my code-:
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string[] excel = new string[250];
DataTable dtt = (DataTable)Session["griddata"]; //griddata is the gridview data from another page
for (int i = 0; i < dtt.Columns.Count; i++)
{
excel[i] = dtt.Columns[i].ColumnName;
}
Session["exceldata"] = excel;
ArrayList mylist= (ArrayList)Session["exceldata"];
DropDownList drd = (DropDownList)GridView2.FindControl("DrdDatabase");
drd.DataSource = mylist;
drd.DataTextField = "GridView";
drd.DataBind();
}
Thanks in Advance :)

Here is the logic which you can use to populate your dropdownlist.
->
Loop at the array.
{
For each item in array
{
add item to dropdownlist.items
}
}
Sorry for not providing the exact code as I dont have .net editor at my disposal right now but you can use the logic to implement it.
regards.

You could simply loop it and add the ListItems programmatically:
DropDownList drd = (DropDownList)GridView1.FindControl("DrdDatabase");
foreach(string colName in mylist)
drd.Items.Add(new ListItem( colName ));
However, are you sure that you find your DropDownList via GridView1.FindControl? I assume you get a NullRefernceException there. Then you need to show us where it actually is.
If it is in a TemplateField of the GridView you should use the RowDataBound event:
private ArrayList ExcelData
{
get {
object excel = Session["exceldata"];
if (excel == null) Session["exceldata"] = new ArrayList();
return (ArrayList)Session["exceldata"];
}
set {
Session["exceldata"] = value;
}
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("DrdDatabase");
foreach (string colName in ExcelData)
ddl.Items.Add(new ListItem(colName));
}
}

Related

How to create dynamic CheckBoxes inside a GridView?

I have a GridView that displays the Approvers list. As shown in below image. I need to show CheckBoxes, if there are multiple Approvers in a column. Is it possible? If yes then how can I achieve it?
E.g The Approvers section has multiple Approver Names in the first row, for which I should show CheckBoxes.
The data displayed in the grid is available in a DataTable and the multiple Approvers are part of a single row hence I can't use TemplateField and display CheckBoxes.
Below is the solution. I could achieve this in method OnRowDataBound(). Not sure if this is the best way.
protected void grdApproverDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string ApproverName = ((Label)e.Row.Cells[2].FindControl("lblANgrd")).Text;
string[] approvers = ApproverName.Split(';');
if (approvers.Count() > 1)
{
((Label)e.Row.Cells[2].FindControl("lblANgrd")).Text = "";
int i = 0;
foreach (var item in approvers)
{
CheckBox ckb = new CheckBox();
ckb.Text = item;
ckb.ID = i.ToString();
ckb.ID = "approvernamesdynamic_"+i.ToString();
ckb.Checked = true;
e.Row.Cells[2].Controls.Add(ckb);
i++;
}
}
}
}

Getting data from GridView after changing the DataSource

I am trying to add the column names of a gridview to a dropdown list.
The problem is when I change the datasource of the gridview, it returns empty.
I am not sure whether the event is working properly, as it does not work with/without it.
I wanted to use the DataBindComplete event, but I could not see it so I tried DataBound instead.
private void BindTable()
{
if (ddTableSearch.SelectedIndex == 0)
{
tblCustomerTableAdapter customerAdapter = new tblCustomerTableAdapter();
GridView2.DataSource = customerAdapter.GetData();
GridView2.DataBind();
}
else if (ddTableSearch.SelectedIndex == 1)
{
tblInvoiceTableAdapter invoiceAdapter = new tblInvoiceTableAdapter();
GridView2.DataSource = invoiceAdapter.GetData();
GridView2.DataBind();
}
else if (ddTableSearch.SelectedIndex == 2)
{
tblEstimateTableAdapter estimateAdapter = new tblEstimateTableAdapter();
GridView2.DataSource = estimateAdapter.GetData();
GridView2.DataBind();
}
}
protected void GridView2_DataBound(object sender, EventArgs e)
{
// Populate dropdown with column names
ddColumnSearch.Items.Clear();
for (int i = 0; i < GridView2.Columns.Count; i++)
{
ddColumnSearch.Items.Add(new ListItem(GridView2.Columns[i].ToString()));
}
}
What am I doing wrong?
The databound event runs for each record in the gridview. So one issue is that each time you are clearing out the items you added before. Another issue is that you need to get the data from the EventArgs instead of from the gridview.columns since those are not there until after all the data is bound. I think all you need to do is get the data from the header row:
protected void GridView2_DataBound(object sender, EventArgs e)
{
// Populate dropdown with column names
if(e.Row.RowType != DataControlRowType.Header) return; //only continue if this is hdr row
ddColumnSearch.Items.Clear();
foreach (TableCell cell in e.Row.Cells)
{
ddColumnSearch.Items.Add(new ListItem(cell.Text));
}
}

Get new dropdownlist boxes On button click in asp.net c# with different Ids and assign datasource, along with selection changed functionality

I need to generate 3 DropDownList Boxes in a row Dynamically on ADD Button click event. Once the DDL is generated i should be able to assign Data source to it and also do DDL-selectedEventChanged functionality on them in c# asp.net.
Below link was exactly am looking for but i couldn't assign data source or i couldn't do any functionality
"Adding multiple DropDownLists with a button click"
any better Ideas please help
if i press Button i need to get 3 DDLs at a time, if i press again it should generate again, so number of clicks= no. of rows with three DDL's in each row
Here is the sample code. The only trick is that you need to load those dynamic controls again after post back. Otherwise, you won't be able to access those.
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
<asp:Button runat="server" ID="AddButton" OnClick="AddButton_Click" Text="Add" />
private List<int> _controlIds;
private List<int> ControlIds
{
get
{
if (_controlIds == null)
{
if (ViewState["ControlIds"] != null)
_controlIds = (List<int>)ViewState["ControlIds"];
else
_controlIds = new List<int>();
}
return _controlIds;
}
set { ViewState["ControlIds"] = value; }
}
private List<string> DataSource
{
get { return new List<string> { "One", "Two", "Three" }; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
var dataSource = DataSource;
foreach (int id in ControlIds)
{
var ddl = new DropDownList();
ddl.ID = id.ToString();
foreach (var data in dataSource)
ddl.Items.Add(new ListItem(data));
PlaceHolder1.Controls.Add(ddl);
}
}
}
protected void AddButton_Click(object sender, EventArgs e)
{
var dataSource = DataSource;
for (int i = 0; i < 3; i++)
{
var reqs = ControlIds;
int id = ControlIds.Count + 1;
reqs.Add(id);
ControlIds = reqs;
var ddl = new DropDownList();
ddl.ID = id.ToString();
foreach (var data in dataSource)
ddl.Items.Add(new ListItem(data));
PlaceHolder1.Controls.Add(ddl);
}
}

What to do to get rows respective to checked checkboxes and then write out the values?

Hello fellow programmers,
Right now I have a webpage which displays a data-table via grid-view. This works fine. I also inserted a column of check-boxes in the beginning of the view. This works fine as well. But when I try to retrieve info from cells from the row whose respective check-box is selected, I get an empty string.
Below are the parts of my code pertinent to this problem:
.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
return;
}
else
{
}
//server connections and whatnot//
OleDbCommand c0 = new OleDbCommand(sql0, myConnection);
myAdapter.SelectCommand = c0;
DataSet ds0 = new DataSet("Contacts");
myAdapter.Fill(ds0);
DataTable dt0 = new DataTable();
dt0 = ds0.Tables["Contacts"];
DataView view = new DataView();
view.Table = dt0;
GV0.DataSource = view;
GV0.DataBind();
myConnection.Close();
}
.cs:
/**
* WHY U NO WORK?!
*/
public void Dedupe(Object o, EventArgs e)
{
String output = "start ";
foreach (GridViewRow row in GV0.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
if (cb.Checked == true)
{
output += row.Cells[1];
}
}
Label1.Text = output;
}
Any help would be greatly appreciated.
Cheers
Just a thought but in your foreach loop you may need to check the RowType property of the current row that you are looping over and make sure that it is set to DataRow. Or you could use a LINQ statement to bring back only rows with a RowType == DataRow and loop over that.
UPDATE Here is a quick sample of what I meant. But in reviewing your code it does not appear that you have any text in the second cell of your gridview, in fact your gridview only has one cell based on the code you provided.
public void Dedupe(Object o, EventArgs e)
{
String output = "start ";
IEnumerable<GridViewRow> rows = from r in GV0.Rows
where r.RowType == DataControlRowType.DataRow
select r;
foreach (GridViewRow row in rows)
{
CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
if (cb.Checked)
{
output += row.Cells[1];
}
}
Label1.Text = output;
}

choose the selected value in a item template

I have a method called BindItems() and this method gets the values to a DataTable and then a GridView is bound to it.
Then I have an itemtemplate in that gridview which contains a drop down, this drop down gets populated from 1 -14 from code behind under Gridview_RowDataBound, now I need to figure a way to get the Quantity value in the DataTable on the other function "BindItems()" and for each Row in the gridview so a SelectedValue = datatable["Quantity"] or something.. how can I do this?
protected void BinItems(int myId)
{
//this data table contains a value "Quantity"
DataTable dt = MyClass.getItems(myId);
uxGrid.DataSource = dt;
uxGrid.DataBind();
}
protected void Gridview1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType.Equals(DataControlRowType.DataRow))
{
DropDownList Myddl = e.Row.FindControl("MyQuantity") as DropDownList;
if (Myddl != null)
{
for (int i = 1; i < 15; i++)
{
Myddl.Items.Add(i.ToString());
}
}
}
//Some how i need to do a SelectedValue = datatable where field = Quantity for each row
}
You need to access the current-being-bound-row's DataItem, which in your case, is a DataRowView (since you are binding to a DataTable):
protected void Gridview1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType.Equals(DataControlRowType.DataRow))
{
DropDownList Myddl = e.Row.FindControl("MyQuantity") as DropDownList;
if (Myddl != null)
{
for (int i = 1; i < 15; i++)
{
Myddl.Items.Add(i.ToString());
}
}
}
//here goes the "magic"
DataRowView dRow = e.Row.DataItem as DataRowView;
if(dRow != null)
{
Myddl.SelectedValue = dRow["Quantity"].ToString();
}
}
you should outside the DataTable dt and then youll be able to access it in the Function

Categories

Resources