I'm looking for some help in a matter i can't solve it.
i created a stored procedure to select data from a table called "applicant"
and it work great
this is the code below:
USE [Josons]
GO
/****** Object: StoredProcedure [dbo].[PROC_GETALLAPPLICANTS] Script Date: 09/03/2013 10:50:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Batch submitted through debugger: SQLQuery25.sql|7|0|C:\Users\supportadmin\AppData\Local\Temp\~vs29E1.sql
ALTER PROCEDURE [dbo].[PROC_GETALLAPPLICANTS]
AS
BEGIN
select ID,FIRSTNAME,LASTNAME,APPLYDATE from APPLICANT order by ID Asc
END
i added a new table called "AF", the two tables are related with a unique column:"applicant_id"
how to make the store procedure to select from 2 tables and show it in one grid view with the same order "ID Asc"
Edit:
aspx file:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPages/MainMasterPage.master"
AutoEventWireup="true" CodeFile="HR.aspx.cs" Inherits="Pages_HR" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div>
<asp:Button ID="btnLogout" CssClass="btnLogoutStyle" runat="server"
Text="Logout" onclick="btnLogout_Click" />
</div>
<div class="divgvDisplayAllApplicantsStyle">
<asp:GridView
ID="gvDisplayAllApplicants"
CssClass="gridviewstyle"
runat="server"
OnRowDataBound="gvDisplayAllApplicants_RowDataBound"
AllowPaging="true"
PageSize="10"
OnPageIndexChanging="gvDisplayAllApplicants_PageIndexChanging"
OnSelectedIndexChanged="gvDisplayAllApplicants_SelectedIndexChanged"
DataKeyNames="ID"
Width="940"
AutoGenerateColumns="false">
<Columns>
<asp:ButtonField CommandName="Select" Visible="false" />
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" />
<asp:TemplateField HeaderText="AF #">
<ItemTemplate>
<%# Eval("AF")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<%# Eval("FIRSTNAME")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<%# Eval("LASTNAME")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Apply Date">
<ItemTemplate>
<%# Eval("APPLYDATE")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</asp:Content>
and the aspx.cs file :
public partial class Pages_HR : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["DisplaySelectedApplicant"] = "DisplaySelectedApplicant";
try
{
if (Session["HR"].ToString() == "" && Request.QueryString["queryStringBackButton"].ToString() == null)
{
Session["DisplaySelectedApplicant"] = "";
Session["HR"] = "";
Response.Redirect("LoginPage.aspx");
}
}
catch (NullReferenceException)
{
Response.Redirect("LoginPage.aspx");
}
}
FillApplicantGridView();
}
#region METHODS
public void FillApplicantGridView()
{
string connstr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
using (SqlConnection sqlconnection = new SqlConnection(connstr))
{
sqlconnection.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "PROC_GETALLAPPLICANTS";
cmd.Connection = sqlconnection;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);
DataTable datatable = new DataTable();
sqlDataAdapter.Fill(datatable);
gvDisplayAllApplicants.DataSource = datatable;
gvDisplayAllApplicants.DataBind();
sqlconnection.Close();
}
}
}
protected void gvDisplayAllApplicants_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get reference to button field in the gridview.
LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "Select$" + e.Row.RowIndex);
e.Row.Style["cursor"] = "hand";
e.Row.Attributes["onclick"] = _jsSingle;
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#93A3B0'; this.style.color='White'; this.style.cursor='pointer'");
e.Row.Attributes.Add("onmouseout", String.Format("this.style.color='Black';this.style.backgroundColor='White';", gvDisplayAllApplicants.RowStyle.BackColor.ToKnownColor()));
}
}
}
protected void gvDisplayAllApplicants_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow selectedRow = gvDisplayAllApplicants.SelectedRow;
int rowIndex = selectedRow.RowIndex;
string Applicant_ID = gvDisplayAllApplicants.DataKeys[rowIndex].Values["ID"].ToString();
Response.Redirect("DisplaySelectedApplicant.aspx?ID=" + Applicant_ID);
}
protected override void Render(HtmlTextWriter writer)
{
foreach (GridViewRow row in gvDisplayAllApplicants.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
ClientScript.RegisterForEventValidation(((LinkButton)row.Cells[0].Controls[0]).UniqueID, "Select$" + row.RowIndex);
}
}
base.Render(writer);
}
protected void gvDisplayAllApplicants_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvDisplayAllApplicants.PageIndex = e.NewPageIndex;
gvDisplayAllApplicants.ShowFooter = false;
gvDisplayAllApplicants.EditIndex = -1;
FillApplicantGridView();
}
#endregion
protected void btnLogout_Click(object sender, EventArgs e)
{
Response.Redirect("LoginPage.aspx");
}
}
Thanks,
If you want all records where both tables have application_id, then use INNER JOIN...
SELECT ap.ID ,
ap.FIRSTNAME ,
ap.LASTNAME ,
ap.APPLYDATE ,
AF.FieldNames
FROM APPLICANT ap
INNER JOIN AF ON ap.applicant_id = AF.applicant_id
ORDER BY ap.ID ASC
If you want to return all Applicants, even if there is no corresponding relation in AF, then use LEFT JOIN...
SELECT ap.ID ,
ap.FIRSTNAME ,
ap.LASTNAME ,
ap.APPLYDATE ,
AF.FieldNames
FROM APPLICANT ap
LEFT JOIN AF ON ap.applicant_id = AF.applicant_id
ORDER BY ap.ID ASC
Example of using ISNULL if no records...
SELECT ap.ID ,
ap.FIRSTNAME ,
ap.LASTNAME ,
ap.APPLYDATE ,
ISNULL(AF.AppFormCourseName, 'No Application as of yet')
FROM APPLICANT ap
LEFT JOIN AF ON ap.applicant_id = AF.applicant_id
ORDER BY ap.ID ASC
Consider calling the AF table something better too, I'm guessing it could be ApplicationForm?
See the explanation here for both Inner Join and Left Join.
ALTER PROCEDURE [dbo].[PROC_GETALLAPPLICANTS] AS
BEGIN
select a.ID,a.FIRSTNAME,a.LASTNAME,a.APPLYDATE,af.* from APPLICANT a join AF af on a.applicant_id = af.applicant_id order by a.ID Asc
END
Related
I can't solve one thing, I want to paint some rows of the GridView depending on a column. I have no problems with this, but when I change the page, I can't get it to paint.
This is how I do the pagination
GridView2.PageIndex = e.NewPageIndex;
loadgrid();
paintpagin(e.NewPageIndex);
So I try to paint it
GridView2.PageIndex = newPageIndex;
foreach (GridViewRow Rowe in GridView2.Rows)
{
CheckBox Rc = (CheckBox)Rowe.FindControl("rdaprobar");
RadioButton Ri = (RadioButton)Rowe.FindControl("rdpendiente");
RadioButton Rd = (RadioButton)Rowe.FindControl("rdCandelar");
if (Rc.Checked == true)
{
GridView2.Rows[Rowe.DataItemIndex].BackColor = ColorTranslator.FromHtml("#bcf5be");
}
}
The even to use for highlights, formatting, etc.?
use the Grid row data bound event.
So, first up, our markup:
<asp:GridView ID="GHotels" runat="server" CssClass="table" AutoGenerateColumns="false"
width="45%" DataKeyNames="ID" OnRowDataBound="GHotels_RowDataBound" AllowPaging="True"
OnPageIndexChanging="GHotels_PageIndexChanging" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:TemplateField HeaderText="HotelName">
<ItemTemplate>
<asp:Label ID="txtHotel" runat="server" Text='<%# Eval("HotelName") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Description" HeaderText="Description" ItemStyle-Width="270" />
</Columns>
<PagerStyle CssClass="GridPager" />
</asp:GridView>
Code to load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL =
"SELECT * FROM tblHotels WHERE Description is not null ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
DataTable rstData = new DataTable();
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
GHotels.DataSource = rstData;
GHotels.DataBind();
}
}
}
Our pager code (and NOTE YOU HAVE the load of the grid before the pager - chec your code!!!).
protected void GHotels_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GHotels.PageIndex = e.NewPageIndex;
LoadData();
}
Ok, we now have this:
Now, I highlight each hotel if it is active. NOTE very careful, I don't have that column "active" in the GV, but it was/is part of the data source. So, for bonus points, I demonstrate how to get/grab/use columns that you don't render or have in the GV, but in fact is part of the data source.
So, our code to highlight, we have this:
protected void GHotels_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// get binding data source
DataRowView gData = e.Row.DataItem as DataRowView;
if ((bool)gData["Active"]) {
// Label tHotel = e.Row.FindControl("txtHotel") as Label;
// tHotel.BackColor = System.Drawing.Color.LightSteelBlue;
e.Row.Cells[2].BackColor = System.Drawing.Color.LightSteelBlue;
}
}
}
So, we now have this:
So do NOT try and loop each row of the GV - use the row data bound to highlight and format as per above.
Data in my GridView inside an UpdatePanel is going out of synch with the database and I can't figure out why. This has resulted in incorrect updates to the database which I have to fix rapidly! Can anyone help?
I have multiple UpdatePanels that have GridViews inside that can be edited by the user. There is a search feature and filter buttons that select queried data from the database and display in the GridView. There is sorting enabled and the "out of synchness" occurs mostly when sorting and then editing a field.
The data comes from a SQL Database. I can update the data directly through OnTextChange option of my TemplateField like this:
<asp:GridView
ID="GridView4"
runat="server"
OnSorting="TaskGridView_Sorting"
AllowSorting="True"
Width="100%" >
<Columns>
<asp:TemplateField SortExpression="name" HeaderText="Name">
<HeaderStyle HorizontalAlign="Left" CssClass="col_name" />
<ItemTemplate>
<asp:TextBox ID="name" AutoPostBack="True" CssClass="col_name" runat="server" Text='<%# Eval("name") %>' Width=180 OnTextChanged="text_change" />
</ItemTemplate>
</asp:TemplateField>
...
I have my gridview inside an UpdatePanel that has these options:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
...
I have enabled partial rendering like this:
<ajaxToolKit:ToolkitScriptManager EnablePartialRendering="true" runat="server" />
I have buttons that filter the data by requerying the database and displaying just the filtered data like this:
DataGrid_Load(DAL.Search_reg_log(OrgText.Text, searchText, searchCol), "reg");
The gridview gets its data loaded like this:
private void DataGrid_Load(DataTable command, string type)
{
DataTable dataTable = new DataTable();
dataTable = command;
string sortDir = ViewState["SortDirection"] as string;
string sortExp = ViewState["SortExpression"] as string;
if(ViewState["SortExpression"] != null)
{
dataTable = resort(dataTable, sortExp, sortDir);
}
try
{
var query = from c in dataTable.AsEnumerable()
where c.Field<string>("status") == "Invoiced" && c.Field<string>("reg_cat_id") != "Archive"
|| c.Field<string>("status") == "Confirmed" && c.Field<string>("reg_cat_id") != "Archive"
select c ;
if(query.Any()){
DataTable t2 = query.CopyToDataTable();
GridView4.DataSource = t2;
GridView4.DataBind();
} else {
GridView4.DataSource = new DataTable();
GridView4.DataBind();
}
}
catch(Exception e) {
ErrorText.Text = "Caught Exception: " + e;
}
...
I have isolated one cause of the data errors which occurs after sorting a column and then
protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExp = ViewState["SortExpression"] as string;
string sortDir = ViewState["SortDirection"] as string;
if(sortDir == "asc" & sortExp == e.SortExpression.ToString())
ViewState["SortDirection"] = "desc";
else
ViewState["SortDirection"] = "asc";
ViewState["SortExpression"] = e.SortExpression.ToString();
if(searchCol != "" && searchText != "")
DataGrid_Load(DAL.Search_reg_log(OrgText.Text, searchText, searchCol), "reg");
else
DataGrid_Load(DAL.reg_log(HeadText.Text, OrgText.Text), "reg");
UpdatePanels();
}
Here is the resort function:
public static DataTable resort(DataTable dt, string colName, string direction)
{
dt.DefaultView.Sort = colName + " " + direction;
dt = dt.DefaultView.ToTable();
return dt;
}
Please help with some direction of what might be causing this.
It looks like you are having some trouble with GridView and updating them. I will post a complete working example below. Start with that and gradually update that code to fit your own needs, like getting data with var query = from c in dataTable.AsEnumerable(). The important thing is to sort the data every time you (re)bind the GridView data. And I'm not sure what is happening inside resort, but you have to use dt.DefaultView.ToTable(); to save the sorting in the DataTable.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server"
DataKeyNames="ID" AllowSorting="true"
OnSorting="GridView1_Sorting"
AutoGenerateColumns="false"
AutoGenerateEditButton="true"
OnRowEditing="GridView1_RowEditing"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<ItemTemplate>
<%# Eval("ID") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="name">
<ItemTemplate>
<%# Eval("name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text=' <%# Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</ContentTemplate>
</asp:UpdatePanel>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
//bind data in an ispostback check
if (!IsPostBack)
{
DataGrid_Load();
}
}
private void DataGrid_Load()
{
//load the datatable data
DataTable dt = source;
//check if the viewsstate existst
if (ViewState["SortExpression"] != null && ViewState["SortDirection"] != null)
{
//sort the datatable before binding it to the gridview
dt.DefaultView.Sort = ViewState["SortExpression"] + " " + ViewState["SortDirection"];
dt.DefaultView.ToTable();
}
//bind the sorted datatable to the gridvidw
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//load the previous sorting settigns
string sortExp = ViewState["SortExpression"] as string;
string sortDir = ViewState["SortDirection"] as string;
//reverse the direction if the column is the same as the previous sort
if (sortDir == "asc" & sortExp == e.SortExpression.ToString())
ViewState["SortDirection"] = "desc";
else
ViewState["SortDirection"] = "asc";
//put the current sort column in the viewstate
ViewState["SortExpression"] = e.SortExpression.ToString();
//rebind data
DataGrid_Load();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
//set the edit index and rebind data
GridView1.EditIndex = e.NewEditIndex;
DataGrid_Load();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//reset the edit index and rebind data
GridView1.EditIndex = -1;
DataGrid_Load();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//use findcontrol to locate the textbox in the edit template
TextBox tb = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");
//get the id of the row from the datakeys
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
//show result for testing
Literal1.Text = "ID: " + id + "<br>Name: " + tb.Text;
//reset the edit index and rebind data
GridView1_RowCancelingEdit(null, null);
}
I know this type of question has been asked multiple times, with solved answers. I've tried them all, but none of it seems to work. Please have a look and maybe help me in understanding where I am going wrong.
.aspx
<asp:view ID="view2" runat="server">
<asp:GridView ID="gvBatches" runat="server" AutoGenerateColumns="False" CssClass="table-hover table" GridLines="None" Width="900px" ShowFooter="True" >
<columns>
<asp:BoundField DataField="bname" HeaderText="Batch Name" />
</columns>
</asp:GridView>
</asp:view>
.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (ViewState["query"] == null)
{
ViewState["query"] = "select course from tblCourses";
}
if (MultiView1.ActiveViewIndex == '1')
{
bindgrid1();
}
bindgrid();
}
}
protected void bindgrid1()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);
DataTable dt1 = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter(ViewState["query"].ToString(), con))
{
sda.Fill(dt1);
}
gvBatches.DataSource = dt1;
gvBatches.DataBind();
}
if (e.CommandName == "viewbat")
{
ViewState["query"] = "select bname from tblBatches where course='" + e.CommandArgument.ToString() + "'";
MultiView1.ActiveViewIndex = 1;
}
Multiview index is changed when a LinkButton(commandName="viewbat") is clicked on a different GridView(gvCourses with datafield="course" and that works fine).
The code throws same error even if the query is changed to simple:
select * from tblBatches
Database design:
Database design is as shown, consists 'bname'
I have a gridview and i want to modify some fields on gridview.This fields value not change when i click on Update button.I tried use Postback control but this problem keep going.How can i solve this problem?
ASPX code
<asp:GridView ID="gview" runat="server" AutoGenerateColumns="False" EnableModelValidation="True" GridLines="Horizontal" OnRowDataBound="gview_RowDataBound" OnRowEditing="gview_RowEditing" OnRowUpdating="gview_RowUpdating" OnRowCancelingEdit="gview_RowCancelingEdit">
<Columns>
<asp:BoundField DataField="SubCategoryId" HeaderText="ID" InsertVisible="False" ReadOnly="True"
SortExpression="SubCategoryId" />
<asp:TemplateField HeaderText="Category">
<ItemTemplate>
<asp:Label ID="lblCategory" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCategory" DataValueField="CategoryId" DataTextField="CategoryName" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CategoryName" HeaderText="Category Name" SortExpression="CategoryName" />
<asp:CommandField ButtonType="Link" EditText="Edit" HeaderText="Edit"
ShowEditButton="True" ShowHeader="False" CancelText="Cancel" UpdateText="Update" />
</Columns>
</asp:GridView>
C# code
protected void gview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl = e.Row.FindControl("lblCategory") as Label;
DropDownList ddl = e.Row.FindControl("ddlCategory") as DropDownList;
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
ddl.DataSource = LoadCategories();
ddl.DataBind();
}
if (lbl != null)
{
lbl.Text = GetCategoryName(Convert.ToInt32(gview.DataKeys[e.Row.RowIndex][0]));
}
}
}
protected void gview_RowEditing(object sender, GridViewEditEventArgs e)
{
gview.EditIndex = e.NewEditIndex;
SubCategoryLoad();
}
protected void gview_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int categoryId, subCategoryId;
string categoryName;
DropDownList ddl = (DropDownList)gview.Rows[e.RowIndex].FindControl("ddlCategory");
subCategoryId = int.Parse(gview.Rows[e.RowIndex].Cells[0].Text);
categoryId = int.Parse(ddl.SelectedValue);
categoryName = gview.Rows[e.RowIndex].Cells[2].Text;
gview.EditIndex = -1;
UpdateSubCategory(subCategoryId,categoryName,categoryId);
SubCategoryLoad();
}
public void SubCategoryLoad()
{
using (SqlConnection conn = new SqlConnection(DataBase.Conn))
{
conn.Open();
string query = "SELECT * FROM dbo.SubCategories";
using (SqlDataAdapter da = new SqlDataAdapter(query, conn))
{
DataTable dt = new DataTable();
da.Fill(dt);
gview.DataSource = dt;
gview.DataBind();
}
}
}
public int UpdateSubCategory(int subCategoryId, string categoryName, int categoryId)
{
using (SqlConnection conn = new SqlConnection(DataBase.Conn))
{
conn.Open();
string query = "UPDATE dbo.SubCategories SET CategoryId = #categoryId, CategoryName = #categoryName WHERE SubCategoryId = #id";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#id", subCategoryId);
cmd.Parameters.AddWithValue("#categoryName", categoryName);
cmd.Parameters.AddWithValue("#categoryId", categoryId);
return (int)cmd.ExecuteNonQuery();
}
}
}
Please check have you bind gridview inside
if(!page.ispostback)
{
}
You must update the data to the actual datasource and rebind it.
If you have updated the values then you shall rebind the GridView again with updated values
mGridView.DataSource = {YOUR DATA SOURCE};
mGridView.DataBind();
EDIT 1:
Does this method being called break there check that
have you set update as
commandText ="Update"
I have a gridview in which every row contains a dropdownlist. I want to bind every dropdownlist dynamically. Can someone tell me how can i do it. Thanks in Advance
If you are using template column then you can bind your drop-down from mark-up using data-binding expressions. For example,
<asp:TemplateField HeaderText="XYZ">
<ItemTemplate>
<asp:DropDownList runat="server" ID="MyDD" DataSourceId="MyDataSource" />
</ItemTemplate>
</asp:TemplateField>
Above is assuming that your drop-down data in constant across rows. If it is changing then you can use data-binding expression such as
<asp:DropDownList runat="server" DataSource='<%# GetDropDownData(Container) %>' DataTextField="Text" DataValueField="Value" />
GetDropDownData will be a protected method in code-behind that will return the data (data-table, list, array) for the given row.
You can use GridView.RowDataBound event (or RowCreated event) in code-behind to fill drop-downs. For example,
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Find the drop-down (say in 3rd column)
var dd = e.Row.Cells[2].Controls[0] as DropDownList;
if (null != dd) {
// bind it
}
/*
// In case of template fields, use FindControl
dd = e.Row.Cells[2].FindControl("MyDD") as DropDownList;
*/
}
}
In addition to the proposed methods, you may also bind your controls within your markup, in this way:
<asp:GridView ID="MyGrid" runat="server" DataSourceID="MyDataSource1">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind ("CustomerId") %>' DataSourceID="CustomersDataSource" DataTextField="CustomerName" DataValueField="CustomerId" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is your gridview
<asp:GridView ID="grvExcelData" runat="server" onrowdatabound="GridView2_RowDataBound">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="DrdDatabase" Width="100px" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and your RowDataBound event for the gridview would be
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
string cities = "maxico,chennai,newdelhi,hongkong";
string [] arr = cities.Split(',');
// Instead of string array it could be your data retrieved from database.
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("DrdDatabase");
foreach (string colName in arr )
ddl.Items.Add(new ListItem(colName));
}
}
protected void gvSalesAppData_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlCurrentPhase = (DropDownList)e.Row.FindControl("ddlCurrentPhase");
DropDownList ddlProductFamily = (DropDownList)e.Row.FindControl("ddlProductFamily");
DropDownList ddlProductGroup = (DropDownList)e.Row.FindControl("ddlProductGroup");
DropDownList ddlETProgramManager = (DropDownList)e.Row.FindControl("ddlETProgramManager");
DropDownList ddlPLMForTheProduct = (DropDownList)e.Row.FindControl("ddlPLMForTheProduct");
TrackingToolObj.BindCurrentPhases(ddlCurrentPhase);
TrackingToolObj.BindCurrentPhases(ddlProductFamily);
TrackingToolObj.BindProductGroups(ddlProductGroup);
TrackingToolObj.GetEmployeesBasedOnRoleTypeId(ddlETProgramManager, (int)OSAEnums.RoleTypes.ProgramManager, false);
TrackingToolObj.GetEmployeesBasedOnRoleTypeId(ddlPLMForTheProduct, (int)OSAEnums.RoleTypes.PLM, false);
}
}
Binding the GridView
Below is the code to Bind the GridView control with data.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string query = "SELECT top 10 * FROM Customers";
SqlCommand cmd = new SqlCommand(query);
gvCustomers.DataSource = GetData(cmd);
gvCustomers.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}