Fetch value from database as selected in dropdownlist - c#

I have a asp page in which i have a dropdown list. The complete list of values is binded in dropdown list from the database table "a". After selecting any value from that dropdown, i save it to database table "b". Now, in 2nd asp page, i want to have that dropdown list with selected value from table "b".
My aspx page:
<asp:DropDownList DataSource='<%# getBankTable() %>' ID="ddlBankName" DataValueField='BANK_ID'
DataTextField="BANK_DESC" SelectedValue='<%# Eval("BANK_ID") %>' AppendDataBoundItems="true"
runat="server">
</asp:DropDownList>
My .cs Page:
protected void Page_Load(object sender, EventArgs e)
{
string sql1 = "SELECT * FROM Master LEFT JOIN BANK ON Master.BANK_ID = Transaction.BANK_ID";
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
ddlBankName.Items.FindByValue(dr["BANK_ID"].ToString()).Selected = true;
}
}
public void getBankTable()
{
ddlBankName.Items.Clear();
ddlBankName.Items.Insert(0, new ListItem("Select", ""));
clsDataAccess cls = new clsDataAccess();
string sql = "SELECT BANK_ID,BANK_DESC FROM Master";
DataTable dt = cls.GetDataTable(sql);
ddlBankName.DataTextField = "BANK_DESC";
ddlBankName.DataValueField = "BANK_ID";
ddlBankName.DataSource = dt;
ddlBankName.DataBind();
}
I am not able to do that. Please help!!

Personally I think it would be best to populate the Dropdown in your CS and set the value there as well.
<asp:DropDownList ID="ddlBankName" DataValueField='BANK_ID' DataTextField="BANK_DESC" AppendDataBoundItems="true" runat="server">
</asp:DropDownList>
In your CS page:
protected void Page_Load(object sender, EventArgs e) {
//Only fill it once on page load:
if (!Page.IsPostBack) {
getBankTable();
string sql1 = "SELECT * FROM Master LEFT JOIN BANK ON Master.BANK_ID = Transaction.BANK_ID";
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
if (dr["BANK_ID"] != null)
{
ddlBankName.Items.FindByValue(dr["BANK_ID"].ToString()).Selected = true;
}
}
}
}
public void getBankTable() {
ddlBankName.Items.Clear();
ddlBankName.Items.Insert(0, new ListItem("Select", ""));
clsDataAccess cls = new clsDataAccess();
string sql = "SELECT BANK_ID,BANK_DESC FROM Master";
DataTable dt = cls.GetDataTable(sql);
ddlBankName.DataTextField = "BANK_DESC";
ddlBankName.DataValueField = "BANK_ID";
ddlBankName.DataSource = dt;
ddlBankName.DataBind();
}

Related

How do i load CheckBoxList from a Selected Value from DropDownList?

i'm trying to do a display database's item(tables, rows, fk,...).
I'm stucking at first few step. I loaded the db's names into a DropDownList. But i tried to load Tables from Selected db's name into CheckBoxList but it shows nothing.
Here are my codes
aspx:
<form id="form1" runat="server" method="get">
<div>
<asp:DropDownList ID="drpListDBName" runat="server" OnSelectedIndexChanged="drpListDBName_SelectedIndexChanged">
</asp:DropDownList>
</div>
<div>
<asp:CheckBoxList ID="chkListTable" runat="server">
</asp:CheckBoxList>
</div>
aspx.cs:
public static String dbname = "";
protected void Page_Load(object sender, EventArgs e)
{
String query = "SELECT * FROM SYS.sysdatabases WHERE name != 'master'" +
" and name != 'tempdb'" +
" and name != 'model'" +
" and name != 'msdb'" +
" and name != 'distribution'";
Program.Connect();
if(!Page.IsPostBack)
{
drpListDBName.DataSource = Program.ExecSqlDataReader(query);
drpListDBName.DataTextField = "name";
drpListDBName.DataBind();
}
}
protected void drpListDBName_SelectedIndexChanged(object sender, EventArgs e)
{
dbname = drpListDBName.SelectedValue.Trim();
String query = "USE " + dbname +
" SELECT * FROM SYS.tables" +
" WHERE is_ms_shipped = 0";
Program.Connect();
if (chkListTable.Items.Count > 0)
chkListTable.Items.Clear();
chkListTable.DataSource = Program.ExecSqlDataReader(query);
chkListTable.DataTextField = "name";
chkListTable.DataBind();
Response.Write(chkListTable);
}
I'm still new to asp.net. Thanks in advance.
Ok, while you could send your 2nd selection (the list of tables) to a check box list?
(and if you needing to select multiple tables - perhaps yes).
but, lets do one better. Lets use two combo boxes. First one, select database, fill 2nd combo box with tables.
Then you select a table, and display the table in a grid.
So, first up is (possbile) is the connection string used. We can assume that you built or setup at least one working connection string to one of the databases on that sql server.
So, project->"my project name settings".
You get this:
So, I have a few already made, but note the [...] button, if you click on that, then VS will launch a connection builder for you (nice and easy). And you can test the connection.
So, we just start out by using TEST4. (note that this DOES put the connection string automatic in web config for you).
Ok, So lets drop in a combo box (to select database).
And then our check box list.
So, we have this markup:
<h4>Select Database</h4>
<asp:DropDownList ID="DropDownList1" runat="server" Width="177px"
DataTextField="name"
DataValueFeild="name"
AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
DataTextField="TABLE_NAME"
DataValueField="TABLE_NAME" >
</asp:CheckBoxList>
And now we have this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
Session["MyCon"] = Properties.Settings.Default.TEST4;
string query = "SELECT * FROM SYS.sysdatabases WHERE name != 'master'" +
" and name != 'tempdb'" +
" and name != 'model'" +
" and name != 'msdb'" +
" and name != 'distribution' ORDER BY Name";
DropDownList1.DataSource = MyRst(query);
DropDownList1.DataBind();
}
public DataTable MyRst(string strSQL)
{
var rst = new DataTable();
using (SqlConnection conn = new SqlConnection((Session["MyCon"] as string)))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rst.Load(cmdSQL.ExecuteReader());
}
}
return rst;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// set connecting string from TEST4 to whatever database selected
string strCon = Session["MyCon"] as string;
string strDB = DropDownList1.SelectedItem.Value;
strCon = strCon.Replace("Initial Catalog = test4;", strDB);
Session["MyCon"] = strCon;
// now load check box list with all tables
string strSQL = #"SELECT TABLE_NAME FROM [" + strDB + "].INFORMATION_SCHEMA.TABLES " +
"WHERE TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME";
CheckBoxList1.DataSource = MyRst(strSQL);
CheckBoxList1.DataBind();
}
So, now we get this:
So, yes, you can set a datatable to check box list. But, some of my databases have quite a few tables - too long (many) check boxes.
So, lets change our code to two combo boxes.
However, we need a "please select" for the combo boxes.
So, our mark up is now this:
<h4>Select Database</h4>
<asp:DropDownList ID="DropDownList1" runat="server" Width="180px"
DataTextField="name"
DataValueFeild="name"
AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<br />
<h4>Select Table</h4>
<asp:DropDownList ID="DropDownList2" runat="server" Width="180"
DataTextField="TABLE_NAME"
DataValueField="TABLE_NAME"
AutoPostBack="true" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged"
>
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" CssClass="table">
</asp:GridView>
Our code is now this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
Session["MyCon"] = Properties.Settings.Default.TEST4;
string query = "SELECT * FROM SYS.sysdatabases WHERE name != 'master'" +
" and name != 'tempdb'" +
" and name != 'model'" +
" and name != 'msdb'" +
" and name != 'distribution' ORDER BY Name";
DropDownList1.DataSource = MyRst(query);
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Please Select", ""));
}
public DataTable MyRst(string strSQL)
{
var rst = new DataTable();
using (SqlConnection conn = new SqlConnection((Session["MyCon"] as string)))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rst.Load(cmdSQL.ExecuteReader());
}
}
return rst;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// set connecting string from TEST4 to whatever database selected
string strCon = Session["MyCon"] as string;
string strDB = DropDownList1.SelectedItem.Value;
strCon = strCon.Replace("Initial Catalog = test4;", strDB);
Session["MyCon"] = strCon;
// now load 2nd cbo box list with all tables
string strSQL = #"SELECT TABLE_NAME FROM [" + strDB + "].INFORMATION_SCHEMA.TABLES " +
"WHERE TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME";
DropDownList2.DataSource = MyRst(strSQL);
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, new ListItem("Please Select", ""));
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
// send results to the Grid
string strSQL = "SELECT * FROM [" + DropDownList2.SelectedItem.Value + "]";
GridView1.DataSource = MyRst(strSQL);
GridView1.DataBind();
}
And now we get this:
So, I used a working connection string to a given database. I quite much assumed that the same information could and would connect to all of them, so I swap out TEST4 database name with any one we select.

ASP.net update DropDownList

I'm adding a value database table then i want to show on DropDownList. This code working when page is loading. But when i add new value to db, dropdownlist doesn't update. I called after adding value but doesn't change. When i don't use !IsPostBack, dropdownlist updating but in this case DataValueField doesnt working.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
.............
listStudent.DataSource = dt;
listStudent.DataTextField = "st";
listStudent.DataValueField = "id";
listStudent.DataBind();
}
Well, you are free to put the DataTextField and the DataValue field in the markup.
(but does not matter one bit at all).
So, say we have this markup:
(drop down, and a button to add a new value).
<asp:DropDownList ID="cboHotels" runat="server"
DataValueField="HotelName" DataTextField="HotelName" AutoPostBack="True" Width="174px" >
</asp:DropDownList>
<asp:Button ID="cmdAdd" runat="server" Text="+" style="margin-left:10px"
OnClick="cmdAdd_Click"
OnClientClick="return AddHotel();" />
<asp:TextBox ID="txtHotelName" runat="server" ClientIDMode="Static" style="display:none"></asp:TextBox>
<script>
function AddHotel() {
myhotel = prompt("Enter New Hotel Name")
if (myhotel != null) {
document.getElementById('txtHotelName').value = myhotel
return true
}
else {
return false
}
}
</script>
So, we have that "+" button beside the drop to add a new row to the database.
So, our code to fill the drop down looks like this:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
LoadCombo();
}
public void LoadCombo()
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT HotelName from tblHotels ORDER BY HotelName",
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
cboHotels.DataSource = cmdSQL.ExecuteReader();
cboHotels.DataBind();
// add a blank (no select row)
cboHotels.Items.Insert(0, new ListItem(""));
}
}
And our code to add a new row looks like this:
protected void cmdAdd_Click(object sender, EventArgs e)
{
// add a new hotel to table
using (SqlCommand cmdSQL =
new SqlCommand("INSERT into tblHotels (HotelName) Values(#Hotel)",
new SqlConnection(Properties.Settings.Default.AccessDB)))
{
cmdSQL.Connection.Open();
cmdSQL.Parameters.Add("#Hotel", SqlDbType.NVarChar).Value = txtHotelName.Text;
cmdSQL.ExecuteNonQuery();
}
LoadCombo(); // re-load combo to show new row
// lets be nice and select the row we just added
cboHotels.ClearSelection();
cboHotels.Items.FindByText(txtHotelName.Text).Selected = true;
}
And we get this:

asp:gridview filter using listbox cannot make multiple selection

I have this asp:gridview in which I show data using mySql stored procedure. I have this listbox named ddlstatus which I use to filter the data. I use viewstate to show data that are selected from the listbox. The problem is I want to make multiple selection on this listbox and show data for each selection made on it, but when it only shows data for the initial selection.
The below is the client side code:
<asp:Label ID="lblstat" Text="status" Visible="false" runat="server"></asp:Label>
<asp:ListBox ID="ddlstatus" runat="server" OnSelectedIndexChanged="DropDownChange" AutoPostBack="true" AppendDataBoundItems="true" SelectionMode="Multiple"></asp:ListBox>
<asp:GridView ID="gdvTM" runat="server" ControlStyle-Width="100%" AutoGenerateColumns="False" DataKeyNames="ID" OnRowDeleting="gdvTM_RowDeleting" PageSize="5" CssClass="cssgridview" AlternatingRowStyle-BackColor="#d5d8dc">
<Columns >
<asp:TemplateField HeaderText="Current Status">
<ItemTemplate >
<asp:Label ID="lblcstat" runat="server" Text='<%# Eval("status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The below is the server side code:
private void BindDropDownList()
{
PopulateDropDown(ddlstatus, lblstat.Text);
}
private void PopulateDropDown(ListBox ddl, string columnName)
{
ddl.Items.Clear();
ddl.DataSource = BindDropDown(columnName);
ddl.DataTextField = columnName;
ddl.DataValueField = columnName;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Please select", "0"));
}
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetTMData");
cmd.CommandType = CommandType.StoredProcedure;
string statusVal = null;
if (ViewState["stat"] != null && ViewState["stat"].ToString() != "0")
{
statusVal = ViewState["stat"].ToString();
}
cmd.Parameters.AddWithValue("statusVal", statusVal);
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
int i = dt.Rows.Count;
gdvTM.DataBind();
this.BindDropDownList();
TableCell cell = gdvTM.HeaderRow.Cells[0];
setDropdownselectedItem(ViewState["stat"] != null ? (string)ViewState["stat"] : string.Empty, ddlstatus);
}
private void setDropdownselectedItem(string selectedvalue, ListBox ddl)
{
if (!string.IsNullOrEmpty(selectedvalue))
{
ddl.Items.FindByValue(selectedvalue).Selected = true;
}
}
protected void DropDownChange(object sender, EventArgs e)
{
ListBox dropdown = (ListBox)sender;
string selectedValue = dropdown.SelectedItem.Value;
switch (dropdown.ID.ToLower())
{
case "ddlstatus":
ViewState["stat"] = selectedValue;
break;
}
this.BindGrid();
}
private DataTable BindDropDown(string columnName)
{
string username = uName.Text;
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlCommand cmd = new MySqlCommand("SELECT DISTINCT (" + columnName + ") FROM approved WHERE tm = #tm AND " + columnName + " IS NOT NULL", con);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("#tm", username);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Below is the MySql stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetTMData`(in statusVal varchar(45))
BEGIN
SELECT *
FROM approved
WHERE (statusVal IS NULL
OR status = statusVal)
order by date desc;
END
How can I make this happen? Thanks in advance.
Please make listbox multiple
<asp:ListBox id="ListBox1"
Rows="6"
Width="100px"
**SelectionMode="Multiple"**
runat="server">
<asp:ListItem Selected="True">Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 4</asp:ListItem>
<asp:ListItem>Item 5</asp:ListItem>
<asp:ListItem>Item 6</asp:ListItem>
</asp:ListBox>
Then in server side
void SubmitBtn_Click(Object sender, EventArgs e)
{
Message.Text = "You chose: <br />";
// Iterate through the Items collection of the ListBox and
// display the selected items.
foreach (ListItem item in ListBox1.Items)
{
if(item.Selected)
{
Message.Text += item.Text + "<br />";
}
}
}
First of all, auto post back not allow you to select multiple items because upto select second item, the postback already happens by first selected item so,
You have to set AutoPostBack="false" for your list box,
<asp:ListBox ID="ddlstatus" runat="server" AutoPostBack="false" AppendDataBoundItems="true" SelectionMode="Multiple"></asp:ListBox>
For collecting multiple selected items we simply choose button for instance, you can collect those items wherever you want,
Then add one button that will call below code
<asp:Button ID="button1" runat="server" OnClick="button1_Click" Text="Click"/>
On above button event handler add below code,
protected void button1_Click(object sender, EventArgs e)
{
var selectedNames = ddlstatus.Items.Cast<ListItem>()
.Where(i => i.Selected)
.Select(i => i.Value)
.ToList();
string selectedValue = string.Join("','", selectedNames);
selectedValue = "'" + selectedValue + "'";
ViewState["stat"] = selectedValue;
}
Then the comma separated items in your ViewState will be used in your stored procedure parameter
string statusVal = null;
if (ViewState["stat"] != null && ViewState["stat"].ToString() != "0")
{
statusVal = ViewState["stat"].ToString();
}
cmd.Parameters.AddWithValue("statusVal", statusVal); //<= Now this string variable contains comma separated list box items values.
If you populate your list box on Page_Load then make sure that you should populate it into !Page.IsPostBack like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Populate your list box here
}
}
And your SP is
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetTMData1`(in statusVal varchar(255))
BEGIN
IF statusVal = '\'\'' THEN
select * from approved;
ELSE
SET #sql = CONCAT('SELECT * FROM approved WHERE status IN (', statusVal, ')');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF ;
END
If you select multiple items from the dropdown then your SP's parameter data look like '\'apple\',\'banana\''. If not then it look like '\''.
There's a few issues that I could spot that may need to be addressed,
Ensure that the method BindDropDownList is only called on a non postback (page refresh), because your method PopulateDropDown is clearing the items on the list which means that viewstate cannot be restored in a postback, hence the probable reason why only one item is being selected.
I'm not 100% of the table schema, but the SQL provided does not seem to be able to query by more than one status properly, you should probably send a comma separated list of values, and in SQL turn them into a temp table so that you effectively search for items with multiple status (you should probably create a new question for this).
Do not use SelectedItem for multiple selections, instead you need to iterate your list items for those that are selected, and you don't need to use ViewState to pass it along (you probably did because of point 1. above). For example you could replace your method BindGrid and DropDownChange with:
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetTMData");
cmd.CommandType = CommandType.StoredProcedure;
string statusVal = null;
foreach (ListItem item in ddlstatus.Items)
{
if(item.Selected)
{
if(statusVal.length > 0)
statusVal += ",";
statusVal += item.Value;
}
}
cmd.Parameters.AddWithValue("statusVal", statusVal);
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
gdvTM.DataBind();
}
protected void DropDownChange(object sender, EventArgs e)
{
this.BindGrid();
}

Want to display list data in html table C#

enter image here
I want to add list data in the html Table.
The list data can be various, so table rows were dynamic and if List size increase user can use paging in table to move next...
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
Date1.Add(sdr["Date"].ToString());
Time.Add(sdr["Time"].ToString());
Event.Add(sdr["Event"].ToString());
Venue.Add(sdr["Venue"].ToString());
}
}
conn.Close();
}
}
for (int i = 0; i < Date1.Count; i++) {
string Date11 = Date1[i];
string Time1 = Time[i];
string Event1 = Event[i];
string Venue1 = Venue[i];
if(Venue1.Contains(country) || Venue1.Contains(Code[0]))
{
Result.Add( Date11 + " " + Time1 + " " + Event1 + " " + Venue1);
}
}
Can someone kindly give me code/hint which can i use in my Project. I will be very thankful to you.
The example below takes care of the following requirements which you've listed in the question:
Generates an HTML table containing your data
Has paging functionality
Supports dynamic columns
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
gvEvents.DataSource = this.GetEvents();
gvEvents.DataBind();
}
}
private DataTable GetEvents()
{
var table = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using(var connection = new SqlConnection(connectionString))
{
using(var command = new SqlCommand("SELECT TOP 100 Date,Time,Event,Venue FROM Event",connection))
{
connection.Open();
var adapter = new SqlDataAdapter(command);
adapter.Fill(table);
connection.Close();
}
}
int rows = table.Rows.Count;//Place breakpoint to make sure table has rows
return table;
}
protected void gvEvents_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvEvents.PageIndex = e.NewPageIndex;
gvEvents.DataSource = this.GetEvents();
gvEvents.DataBind();
}
.ASPX:
<form id="form1" runat="server">
<asp:GridView ID="gvEvents" runat="server" AllowPaging="true" PageSize="2" OnPageIndexChanging="gvEvents_PageIndexChanging">
</asp:GridView>
</form>
Output:

Grab SelectedValue of Dropdownlist in Gridview

Creating a list of users that haven't updated their job title in a Gridview. I want the list to have a dropdown filled with all the possible title selections and a button next to the dropdown. Then a person can come in and change the title in the dropdown hit the button and its updated and removed from the list.
I have all of this the way I want it to look but I'm trying to figure out how to pass the SelectedValue of the dropdown box in that row to the code behind OnClick. As you can see below the closest I can get is pass the row number in the CommandArgument. Any suggestions how I can get the SelectedValue of the dropdown of that specific row to the OnClick?
EDIT: Maybe I should be using OnRowCommand instead of OnClick?
Looks like this currently:
John Doe | DropdownList Button
Jane Doe | DropdownList Button
Joe Doe | DropdownList Button
Jeff Doe | DropdownList Button
ASPX
<asp:GridView runat="server" ID="TitleView" OnRowDataBound="TitleView_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Fullname" HeaderText="Fullname" />
<asp:TemplateField>
<ItemTemplate>
<div class="input-append"><asp:DropDownList CssClass="span5" ID="TitleList" runat="server">
</asp:DropDownList>
<asp:Button ID="lbnView" runat="server" Text="Update" CssClass="btn btn-primary" OnClick="btn_Clicked"
CommandArgument='<%# ((GridViewRow)Container).RowIndex %>'></asp:Button></div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
public void bindTitleView()
{
using (SqlConnection conn = new SqlConnection(""))
{
SqlCommand cmd = new SqlCommand(#"SELECT U.First + ' ' + U.Last as Fullname, U.UserID, T.Name FROM Employees U LEFT JOIN Titles T ON U.Title = T.ID WHERE U.Active = '1' AND U.Title = '92' ORDER BY Fullname ASC", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet);
TitleView.DataSource = myDataSet;
TitleView.DataBind();
}
}
protected void TitleView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("TitleList");
using (SqlConnection conn = new SqlConnection(""))
{
SqlCommand cmd = new SqlCommand(#"SELECT ID, Name FROM Titles ORDER BY Name ASC", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable myDataSet = new DataTable();
adp.Fill(myDataSet);
ddl.DataSource = myDataSet;
ddl.DataTextField = "Name";
ddl.DataValueField = "ID";
ddl.DataBind();
}
}
}
protected void btn_Clicked(object sender, EventArgs e)
{
String rowid = ((Button)sender).CommandArgument;
}
SOLUTION: The answer I approved below worked for me once I added !IsPostBack to the Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindTitleView();
}
You can do like that:
protected void btn_Clicked(object sender, EventArgs e)
{
int line = ((GridViewRow)((Button)sender).Parent.Parent).RowIndex;
DropDownList drp = ((DropDownList)TitleView.Rows[line].FindControl("TitleList"));
//Continue the method
}
In your btn_click write the following code
protected void btn_Clicked(object sender, EventArgs e)
{
Button Sample = sender as Button;
GridViewRow row = Sample.NamingContainer as GridViewRow;
DropDownList drp = row.FindControl("TitleList") as DropDownList;
//Now use drp.SelectedValue
}
}
Let me know if this isnt what you are looking for.

Categories