Load Databind DropDownList inside ListView - c#

I have a ListView control that contains a DropDownList control inside the ItemTemplate tag.
I am trying to load the existing list items to the DropDownList using the codes below inside the ItemCommand event of the ListView control:
DropDownList ddlItem = (DropDownList)e.Item.FindControl("ddlItem");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ID, Name FROM Items";
SqlDataReader data = cmd.ExecuteReader();
ddlItem.DataSouce = data;
ddlItem.DataTextField = "Name";
ddlItem.DataValueField = "ID";
ddlItem.DataBind();
con.Close();
After binding the items, I want to choose the selected items based from the database records.
Am I missing something?

You should do that in the ListView's ItemDataBound event instead. You will find your DropDownList there via e.Item.FindControl("ddlItem") get the underlying datasource for that item via e.Item.DataItem. Use the debugger if you're unsure about the types.
protected void ListView1_ItemDataBound(Object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
DropDownList ddlItem = (DropDownList) e.Item.FindControl("ddlItem");
var rowView = e.Item.DataItem as DataRowView;
int id = (int)rowView["ID"]; // whatever
// get data from id ...
//ddlItem.DataSouce = data;
//ddlItem.DataTextField = "Name";
//ddlItem.DataValueField = "ID";
//ddlItem.DataBind();
}
}

Related

Populate dropdown from database, which is place inside Gridview in Windows Application using c#

How to populate a drop down from database which is placed inside a gridview and handle the selected index change event of that drop down in windows application using c#
You can bind the IList implementation with the dropdown or combo box.
Instead of enum.getvalues, you can bind any IList and specify the display property name.
DataGridViewComboBoxColumn CreateComboBoxWithEnums()
{
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.DataSource = Enum.GetValues(typeof(Title));
combo.DataPropertyName = "Title";
combo.Name = "Title";
return combo;
}
Then use below code to add the column to the grid view columns collection
dataGridView1.Columns.Add(CreateComboBoxWithEnums());
Please note that Unlike the ComboBox control, the DataGridViewComboBoxCell does not have SelectedIndex and SelectedValue properties. Instead, selecting a value from a drop-down list sets the cell Value property.
Reference: this documentation
I hope you have already got how to populate combobox inside Datagridview. You can try this to handle selected index change of Datagridview Combobox as shown below.
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
int column=excelGridview.CurrentCell.ColumnIndex;
int row = excelGridview.CurrentCell.RowIndex;
int country = Convert.ToInt32(((ComboBox)sender).SelectedValue);
if (column == 7)
{
MyConnect myCnn = new MyConnect();
String connString = myCnn.getConnect().ToString();
SqlConnection conn;
SqlCommand command;
conn = new SqlConnection(connString);
command = new SqlCommand();
if (country > 0)
{
try
{
conn.Open();
string query = "select regionID FROM countryinfo country WHERE country.ID=" + country + "";
command = new SqlCommand(query, conn);
SqlDataReader reader = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
var currentcell = excelGridview.CurrentCellAddress;
DataGridViewComboBoxCell cel = (DataGridViewComboBoxCell)excelGridview.Rows[currentcell.Y].Cells[8];
cel.Value = Convert.ToInt64(dt.Rows[0]["regionID"]);
conn.Close();
}
catch (Exception ex1)
{
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
}
}
catch (Exception) { }
}
You can get help from here
It looks like as shown in below image

Formatting Cells on Gridview from SQL Data Reader

I have a Grid view which populates through my SQL data reader
Grid View:
<asp:GridView ID="gridviewALL" runat="server" OnItemDataBound="Search_ItemDataBound">
</asp:GridView>
SQL Data Reader:
SqlCommand cmd = new SqlCommand("SELECT en.dpCreatedDT AS 'Time Received', en.enStatusCH AS 'Status', en.enNotificationNoNI AS 'LSBUD Ref', cm.cmpersonfirstch AS 'First Name', cm.cmPersonLastCH AS 'Last Name', cm.cmcompanynamech AS 'Company' FROM dp_enquiry en JOIN dp_caller_master cm ON (en.encmcallerkeyfk = cm.cmCallerKeyNI) WHERE en.ennotificationnoni = #JobnoALL", conn);
try
{
SqlParameter search = new SqlParameter();
search.ParameterName = "#JobnoALL";
search.Value = JobnoALL.Text.Trim();
cmd.Parameters.Add(search);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
gridviewALL.DataSource = dt;
gridviewALL.DataBind();
}
I'm trying to change the format of a cell in the grid view when the text equals a value, I've done this using a listview before but the Gridview steps seems different. I have the following which doesn't seem to be working any suggestions?
private void Search_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
string CurrentColumn = e.Item.Cells[1].Text;
if (CurrentColumn == "PROC")
{
e.Item.Cells[1].Text = "Creating PDF";
}
else if (CurrentColumn == "CLOS")
{
e.Item.Cells[1].Text = "Complete";
e.Item.Cells[1].ForeColor = System.Drawing.Color.Green;
}
}
It must be reading the header, you need to check if its a DataRow:-
if (e.Row.RowType == DataControlRowType.DataRow)
{
string CurrentColumn = e.Item.Cells[1].Text;
//your code goes here..
}
Also, I would suggest you to use DataBinder.Eval method instead to avoid hard-coding of cell index as it may result in error if order of columns change.
string CurrentColumn = DataBinder.Eval(e.Row.DataItem, "yourColumnName").ToString();
Update:
Just noticied you are using ItemDataBound which is an event for DataGrid and not Gridview. Use RowDataBound event instead:-
<asp:GridView ID="gridviewALL" runat="server" OnRowDataBound="gridviewALL_RowDataBound">
</asp:GridView>
Your rowDataBound event should look like this:-
protected void gridviewALL_RowDataBound(object sender, GridViewRowEventArgs e)
{
//your code here
}

How to change the default value of a data grid view combo box column with selected value from itself

i have a data grid view combo box column in my data grid view. On on load event of form i am loading the companies name in combo box column and through cell formatting event i am giving the default value to data grid view combo box column.
Now if i select different value from combo box column it does not get reflected. means only default value is there.
My code for on load and cell formatting is
public void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
SqlConnection c = new SqlConnection();
c.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='D:\\Documents\\Visual Studio 2008\\Projects\\Accounts\\Accounts\\Database1.mdf';Integrated Security=True;User Instance=True";
c.Open();
if (e.ColumnIndex == 1 && Viewcashvoucher.mk != "")
{
string mky = Viewcashvoucher.mk;
string q = "select * from lgr where main_key ='" + mky + "'";
SqlCommand cmd = new SqlCommand(q, c);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
e.Value = dr["account_n"].ToString();
}
}
c.Close();
}
and on load event is
private void Cash_Voucher_Load(object sender, EventArgs e)
{
string mky = Viewcashvoucher.mk;
SqlConnection c = new SqlConnection();
c.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='D:\\Documents\\Visual Studio 2008\\Projects\\Accounts\\Accounts\\Database1.mdf';Integrated Security=True;User Instance=True";
c.Open();
string q = "select max(date) from lgr ";
SqlCommand cmd = new SqlCommand(q, c);
SqlDataReader rd = cmd.ExecuteReader();
try
{
if (rd.Read())
{
DateTime date = rd.GetDateTime(0);
if (date != null)
{
tbdate.Text = date.ToShortDateString();
}
}
}
catch (Exception ex)
{
tbdate.Text = DateTime.Now.ToShortDateString();
}
c.Close();
c.Open();
string q1 = "select account_n from master";
SqlCommand cmd1 = new SqlCommand(q1, c);
SqlDataReader rd1 = cmd1.ExecuteReader();
DataGridViewComboBoxColumn acname = dataGridView1.Columns[1] as DataGridViewComboBoxColumn;
while (rd1.Read())
{
acname.Items.Add(Convert.ToString(rd1["account_n"]));
}
}
actually i am using same data grid view for insert and update operation. i want that as user select different value from combo box list the default value should be replaced by selected one.
thanks in advance...
you can also bind the DataBindingComplete event. The only difference in previous and this answer is #Junaith bind the RowAdded event mean it will call the function every time you add the row. and here in mycase I bound DataBindingComplete event which will fire after the grid is full loaded mean this will call only once and that time it will check the all the checkbox in first column of the grid for all the lines.
mygrid.DataBindingComplete +=
new DataGridViewBindingCompleteEventHandler(mygrid_DataBindingComplete);
then and you have to define a function name as mygrid_DataBindingComplete
private void mygrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridView temp = (DataGridView)sender;
foreach (DataGridViewRow rw in temp.Rows)
{
// here 0 indicating the checbox column is the first column in grid
// first column so index would be 0. true will check the checkbox
rw.Cells[0].Value = true;
}
}
CellFormatting event handler is not the right place to set the default value. CellFormatting occurs whenever the content of the cells needs to be formated for display. Whenever you the change the value in the combobox and accept the value, this event is raised and the default value code resets the user selection.
In DataGridView.RowsAdded you could set the defalut value for the combobox cell for the newly added row(s)
Sample Code:
void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
for (int i = e.RowIndex; i < (e.RowIndex+e.RowCount); i++)
{
dataGridView1.Rows[i].Cells[comboboxcolumn_index].Value = defaultvalue;
}
}
hai you can Just use this on RowAdded Event or DataGridview comboboxcolumn creation time. It will Set the Default Value
comboboxcolumn_Name.DefaultCellStyle.NullValue = "Please Select";
void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
for (int i = e.RowIndex; i < (e.RowIndex+e.RowCount); i++)
{
comboboxcolumn_Name.DefaultCellStyle.NullValue = "Please Select";
}
}

Using Sql data after binding to repeater

I wish to use some data from the database after binding my query to a repeater. But i'm not sure how i am supposted to do this. Here is my code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("SELECT * FROM kontakt", conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
Repeater_Beskeder.DataSource = reader;
Repeater_Beskeder.DataBind();
foreach (RepeaterItem row in Repeater_Beskeder.Items)
{
if (reader.Read())
{
Panel Vis_Panel = (Panel)row.FindControl("Panel_Vis_Besked");
if (Request.QueryString["id"].ToString() == reader["id"])
{
Vis_Panel.Visible = true;
}
}
}
conn.Close();
My reader wont work as it's allready been binded to my repeater, so i'm quite lost.
I hope some of you have another solution to this problem.
ItemDataBound Event Occurs after an item in the Repeater control is data-bound but before it is rendered on the page.
void Repeater_Beskeder_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {
// This event is raised for the header, the footer, separators, and items.
// Execute the following logic for Items and Alternating Items.
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
Panel Vis_Panel = (Panel)row.FindControl("Panel_Vis_Besked");
if (Request.QueryString["id"].ToString() == reader["id"])
{
Vis_Panel.Visible = true;
}
}
}

DropdownList DataSource

Hi everyone I have problem about dropdown list. I am using dropdown list with datasource. How can I get that value which I selected ?
// I need a if statement here because my programme doesn't know which value of dropdown list selected and I don't know how to use this with datasource.
if(//if I select quiz 1 from dropdown list ,quiz 1 should list questions.)
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString);
string chooce = "Select Quiz from tblQuiz where Quiz=1 ";
SqlCommand userExist = new SqlCommand(chooce, con);
con.Open();
int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());
if (temp == 1)
{
if (rbList.Items[0].Selected == true)
{
string cmdStr = "Select Question from tblQuiz where ID=1";
SqlCommand quest = new SqlCommand(cmdStr, con);
lblque.Text = quest.ExecuteScalar().ToString();
con.Close();
}
You can bind the DropDownList in different ways by using List, Dictionary, Enum, DataSet DataTable.
Main you have to consider three thing while binding the datasource of a dropdown.
DataSource - Name of the dataset or datatable or your datasource
DataValueField - These field will be hidden
DataTextField - These field will be displayed on the dropdwon.
you can use following code to bind a dropdownlist to a datasource as a datatable:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from tblQuiz", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
DropDownList1.DataTextField = "QUIZ_Name";
DropDownList1.DataValueField = "QUIZ_ID"
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
if you want to process on selection of dropdownlist, then you have to change AutoPostBack="true" you can use SelectedIndexChanged event to write your code.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string strQUIZ_ID=DropDownList1.SelectedValue;
string strQUIZ_Name=DropDownList1.SelectedItem.Text;
// Your code..............
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
drpCategory.DataSource = CategoryHelper.Categories;
drpCategory.DataTextField = "Name";
drpCategory.DataValueField = "Id";
drpCategory.DataBind();
}
}
Refer to example at this link. It may be help to you.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.aspx
void Page_Load(Object sender, EventArgs e)
{
// Load data for the DropDownList control only once, when the
// page is first loaded.
if(!IsPostBack)
{
// Specify the data source and field names for the Text
// and Value properties of the items (ListItem objects)
// in the DropDownList control.
ColorList.DataSource = CreateDataSource();
ColorList.DataTextField = "ColorTextField";
ColorList.DataValueField = "ColorValueField";
// Bind the data to the control.
ColorList.DataBind();
// Set the default selected item, if desired.
ColorList.SelectedIndex = 0;
}
}
void Selection_Change(Object sender, EventArgs e)
{
// Set the background color for days in the Calendar control
// based on the value selected by the user from the
// DropDownList control.
Calendar1.DayStyle.BackColor =
System.Drawing.Color.FromName(ColorList.SelectedItem.Value);
}
It depends on how you set the defaults for the dropdown. Use selected value, but you have to set the selected value. For instance, I populate the datasource with the name and id field for the table/list. I set the selected value to the id field and the display to the name. When I select, I get the id field. I use this to search a relational table and find an entity/record.

Categories

Resources