asp.net dropdownlist in gridview - asp.net

im working on an asp.net website with a gridview.
The gridview has data from an sql database.
Like:
Cuntry----Name
USA--------John
England----Frank
...
The data is loaded in to the gridview like this:
SqlCommand cmd;
cmd = new SqlCommand();
cmd.Connection = sqlConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_loadData";
sqlConn.Open();
dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
So, in the name column, i want a dropdownlist. And I want the dropdownlist with the corresponding value from the database selected.
How can I do this?
Thanks

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:DropDownList Width="50" runat="server" id="ddlCountry" AutoPostBack="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
In Code-behind
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Checking whether the Row is Data Row
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Finding the Dropdown control.
Control ctrl = e.Row.FindControl("ddlCountry");
if (ctrl != null)
{
DropDownList dd = ctrl as DropDownList;
//Here Bind with country list
dd.DataSource = lst;
//Put here the object properties name
dd.DataValueField = "idCountry";
dd.DataTextField = "nameCountry";
dd.DataBind();
//Here add the code to select the current user country in the list
int idUserCountry = 10;
dd.Items.FindByValue(idUserCountry).Selected = true;
}
}
}

Related

method of populate dropdownlist inside gridview

If i want to populate a DropdownList in a GridView what will be the best way? use GridView 'OnRowDataBound' event and fetch query everytime to db or get all data first and put it on datatable and do further work from this datatable ?
As your question is unclear about your requirement, I assume that you want to bind dropdownlist inside the Gridview using OnRowDataBound event of gridview.
So here are the steps:-
Add a Gridview HTML in your aspx page with DropDownList in ItemTemplate of TemplateField.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField HeaderText="Name" DataField="ContactName" />
<asp:TemplateField HeaderText = "Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>' Visible = "false" />
<asp:DropDownList ID="ddlCountries" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then you need to bind the gridview with records which will come from the database.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData("SELECT ContactName, Country FROM Customers");
GridView1.DataBind();
}
}
private DataSet GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
Then the code for OnRowDataBound will follow like below :-
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlCountries = (e.Row.FindControl("ddlCountries") as DropDownList);
ddlCountries.DataSource = GetData("SELECT DISTINCT Country FROM Customers");
ddlCountries.DataTextField = "Country";
ddlCountries.DataValueField = "Country";
ddlCountries.DataBind();
//Add Default Item in the DropDownList
ddlCountries.Items.Insert(0, new ListItem("Please select"));
//Select the Country of Customer in DropDownList
string country = (e.Row.FindControl("lblCountry") as Label).Text;
ddlCountries.Items.FindByValue(country).Selected = true;
}
}
See the Reference link for your reference
Also see the Working demo for your reference
Hope that helps.

set text to textbox based on selected value from dropdownlist in gridview asp net

I have one Dropdown and one textBox in my gridview.
gridview contains some subject name and in database there is fees for particular
subject. I want to show that Fees into textbox on every value selected for dropdown.
i have done the same functionality which gives exact output what i want but not immediately after selection of subject, it gives value on button click.
may be i have done something wrong but not found exact solution please help.
ASPX code :
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowDataBound="Gridview1_RowDataBound" CssClass="EU_DataTable">
<Columns>
<asp:TemplateField HeaderText="Program Name">
<ItemTemplate>
<asp:DropDownList ID="ddl_ProgList" runat="server" AppendDataBoundItems="true" OnSelectedIndexChanged="ddl_ProgList_SelectedIndexChanged" ControlStyle-Width="160px">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Fees">
<ItemTemplate>
<asp:TextBox ID="txt_fees" runat="server" ControlStyle-Width="75px"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind :
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Control ctrl = e.Row.FindControl("ddl_ProgList");
if (ctrl != null)
{
DropDownList dd = ctrl as DropDownList;
//SqlConnection conn = new SqlConnection(connStr);
clsProg_TB objprg = new clsProg_TB();
objprg.Center_Code = ddl_centerCode.SelectedItem.ToString();
DataSet ds = clsUserLogicLayer.LoadPrograms(objprg);
dd.DataTextField = "prg_Name";
dd.DataValueField = "prg_Name";
dd.DataSource = ds.Tables[0];
dd.DataBind();
}
}
}
protected void ddl_ProgList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
foreach (GridViewRow row in Gridview1.Rows)
{
Control ctrl = row.FindControl("ddl_ProgList") as DropDownList;
if (ctrl != null)
{
DropDownList ddl1 = (DropDownList)ctrl;
if (ddl.ClientID == ddl1.ClientID)
{
TextBox txt2 = row.FindControl("txt_fees") as TextBox;
clsProg_TB objprg = new clsProg_TB();
objprg.Center_Code = ddl_centerCode.SelectedItem.ToString();
objprg.Prg_Name = ddl1.SelectedItem.ToString();
DataSet ds = clsUserLogicLayer.getProgFees(objprg);
if (ds.Tables[0].Rows.Count != 0)
{
txt2.Text = ds.Tables[0].Rows[0][0].ToString();
}
}
}
}
}
You can try to update Row and the bind the gridview again. You also need to set GridView.SetEditRow() before starting editing. Another way is to update your dataTable and bind it again.
protected void ddl_ProgList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
foreach (GridViewRow row in Gridview1.Rows)
{
GridView.SetEditRow(row.RowIndex);
Control ctrl = row.FindControl("ddl_ProgList") as DropDownList;
if (ctrl != null)
{
DropDownList ddl1 = (DropDownList)ctrl;
if (ddl.ClientID == ddl1.ClientID)
{
TextBox txt2 = row.FindControl("txt_fees") as TextBox;
clsProg_TB objprg = new clsProg_TB();
objprg.Center_Code = ddl_centerCode.SelectedItem.ToString();
objprg.Prg_Name = ddl1.SelectedItem.ToString();
DataSet ds = clsUserLogicLayer.getProgFees(objprg);
if (ds.Tables[0].Rows.Count != 0)
{
txt2.Text = ds.Tables[0].Rows[0][0].ToString();
}
}
}
Gridview1.UpdateRow(row.RowIndex, false);
}
Gridview1.DataBind();
}

lisbox1.selected index changed to -1 autometically

I have a listbox in asp.net and I am binding list Items from database. I have a button named "submit". Now when pages loads I am getting desired values in listbox, but when I am selecting any value and pressing submit button it sets listbox's selected index to -1.
can anyone help me to get proper index value?
<div class="PageRight">
<asp:ListBox ID="ListOfSql" runat="server" SelectionMode="Single" DataTextField="sql_name"
DataValueField="sql_text" Style="margin-left: 0px" Width="205px" EnableViewState="true"
OnSelectedIndexChanged="ListOfSql_SelectedIndexChanged">
</asp:ListBox><br />
<asp:Button ID="btnPreSqlExe" runat="server" Text="Sumbit"
onclick="btnPreSqlExe_Click">
</asp:Button>
</div>
and .cs page is like
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
txtQuery.Text = ListOfSql.SelectedItem.Value.ToString();
}
To Bind Data in listBox I am using following Code
Private void loadSqlList()
{
if (!IsPostBack)
{
conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
string preSql = "select sql_name, sql_text from cn_sql_log order by sql_name";
OracleDataAdapter da = new OracleDataAdapter(preSql, conn);
da.Fill(ds);
ListOfSql.DataSource = ds;
ListOfSql.DataTextField = "Sql_Name";
ListOfSql.DataValueField = "sql_Text";
ListOfSql.DataBind();
ListOfSql.SelectedIndex = 0;
conn.Close();
}
and calling loadSqlList() on page_load

how to make radiobutton selected in gridview depend on value return from dataset?

i have web application in which i used gridview. In gridview i used radiobutton list this radiobutton list has two item Yes and No.i want to select one item from these two depend on value i get from dataset at the time binding.suppose my column name is is_selected and it returns True then in radiobutton list Yes should be checked.
This is code i have tried myself but no success,
<asp:TemplateField HeaderText="Ready To Join?" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:RadioButtonList ID="rbd_join" AutoPostBack="true" runat="server"
RepeatDirection="Horizontal" BorderStyle="None" BorderWidth="0px" BorderColor="Transparent"
onselectedindexchanged="rbd_join_SelectedIndexChanged"
DataValueField="is_selected">
<asp:ListItem Text="Yes" Value="1" ></asp:ListItem>
<asp:ListItem Text="No" Value="0"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
After Edit
Addition
.cs file
on button click event this is code:
Dataset ds=new Dataset();
ds=bindgrid();
if(ds.table[0].rows.count>0)
{
grd_view.Datasource=ds.tables[0];
grd_view.Databind();
}
public Dataset bindgrid()
{
SqlParameter stud_ID = new SqlParameter("#student_id", SqlDbType.Int);
stud_ID.Value = 1;
SqlCommand cmdSql = new SqlCommand();
cmdSql.CommandType = CommandType.StoredProcedure;
cmdSql.CommandText = "usp_select_candidate_inplacement_byAdmin";
cmdSql.Parameters.Add(stud_ID);
DataSet ds = new DataSet();
DataClass dl = new DataClass();
ds = dl.dsSelect(cmdSql);
return ds;
}
and this is event i added
protected void grd_view_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var radioList = e.Row.FindControl("rbd_join") as RadioButtonList;
var myobject = e.Row.DataItem as DataRow;
bool is_sel = bool.Parse(myobject ["is_selected"].ToString());
radioList.SelectedValue = is_sel ? "1" : "0";
}
}
You need to use the RowDataBound event:
ASPX
<asp:GridView ..... OnRowDataBound="gv_RowDataBound"
Code behind
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var radioList = e.Row.FindControl("rbd_join") as RadioButtonList;
// this will be the object that you are binding to the grid
var myObject = e.Row.DataItem as DataRowView;
bool isSelected = bool.Parse(myObject["is_selected"].ToString());
radioList.SelectedValue = isSelected ? "1" : "0";
}
}

how to get grid view selected row's DataBase id

I have GridView, which is not auto generating columns. In GridView there are 3 columns: one for Checkbox(to delete selected row from DataTable),
one for edit link button(to edit current row),
and the third one is for showing data from DataTable.
I am binding it from DataTable.
I have a primary key in DataTable.
Now my problem is when I am clicking on edit link button I am not getting primary key(id) from
datatable for selected row in grid view (i think row is not selected when i am clicking on edit link button). I cant take row index to match it with datatable primary key as data bound in GridView is filtered.
What I have tried is, I created one more column in grid view as hidden which is primary key column from DataTable. But for that too I am not getting data in hidden column of row which is clicked for edit.
Someone please help with a new idea, or solution for what i am trying.. thanx in advance.
Plese try as follow.. for update, selected ID can be got in gv_RowCommand event. For delection [multiple select checbox] check in btnDelete_Click, enter code here
--------------aspx code--------------------------------
<asp:Button ID="btnDelete" runat="server" Text="Delete"
onclick="btnDelete_Click" />
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" onrowcommand="gv_RowCommand"
onrowupdating="gv_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Update">
<ItemTemplate>
<asp:LinkButton runat="server" CommandArgument='<%# Eval("ID") %>' CommandName="Update" text="Update" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="NAME" HeaderText="Name" />
</Columns>
</asp:GridView>
---------------code behind---------------------------
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindData();
}
private void BindData()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("NAME");
DataRow dr = dt.NewRow();
dr[0] = "1";
dr[1] = "James";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "2";
dr[1] = "Paul";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "3";
dr[1] = "Mary";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "4";
dr[1] = "Susan";
dt.Rows.Add(dr);
gv.DataSource = dt;
gv.DataBind();
}
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
string id = e.CommandArgument.ToString();
}
}
protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void btnDelete_Click(object sender, EventArgs e)
{
string idList = "";
for (int i = 0; i < gv.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gv.Rows[i].FindControl("chkSel");
if (chk != null && chk.Checked)
idList += gv.DataKeys[i].Value.ToString() + ",";
}
}

Resources