Convert GridView.DataSource with DateTime column to datatable - c#

I'm trying eventually to sort the gridview, But when I convert:
DataTable dt = (DataTable)gridAllTests.DataSource;
There's an exeption - can't convert object DateTime to String.
The datasource comes from database sql server, using Entity
GridView:
<asp:GridView ID="gridAllTests" runat="server" AutoGenerateColumns="false"
DataKeyNames="testId" AllowSorting="true">
<Columns>
<asp:BoundField DataField="courseName" HeaderText="Course" SortExpression="courseName"/>
<asp:BoundField DataField="onDate" HeaderText="Date" SortExpression="onDate"
DataFormatString="{0:d}" HtmlEncode="false"/>
<asp:BoundField DataField="lastRegisterDate" HeaderText="LastDate"
SortExpression="lastRegisterDate" DataFormatString="{0:d}" HtmlEncode="false"/>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnRegister" runat="server" text="Register"
CommandName="Register" CommandArgument='<%#Eval("testId") %>' />
<asp:Literal ID="litAlreadyRegisterd" runat="server" Text="Registered"/>
<asp:Literal ID="litTooLate" runat="server" Text="Registration Over"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
SecondTestEntities1 db = new SecondTestEntities1();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
User currUser = (User)Session["user"];
gridAllTests.DataSource = from test in db.Tests
select new
{
testId= test.TestId,
courseName = test.Course.Name,
onDate = test.OnDate,
lastRegisterDate = test.LastRegisterDate
};
try
{
gridAllTests.DataBind();
DataTable dt = (DataTable)gridAllTests.DataSource;
Session["taskTable"] = dt;
}
catch (Exception err)
{
lblError.Text = err.Message.ToString();
}
}
if (gridAllTests.Rows.Count < 1)
{
lblMessage.Visible = true;
}
}

Try this way
DataView dv=(DataView) from test in db.Tests
select new
{
testId= test.TestId,
courseName = test.Course.Name,
onDate = test.OnDate,
lastRegisterDate = test.LastRegisterDate
};
gridAllTests.DataSource = dv;
DataTable dt = new DataTable();
DataSourceSelectArguments args = new DataSourceSelectArguments();
DataView dv = new DataView();
dv = (DataView)dv.Select(args);// This SqlDataSourceObject means your sql query return object ,like dataset or dataview, etc
dt = dv.ToTable();

Try converting your date objects to strings
test.OnDate.ToString(//format here);
test.LastRegisterDate.ToString(//format here);
I think I've come across a similar issue where DataTable doesn't know how to deal with DateTime objects.

if (!Page.IsPostBack)
{
User currUser = (User)Session["user"];
// Dataset dsGrdDource = new Dataset();
IEnumerable<DataRow> result = from test in db.Tests
select new
{
testId= test.TestId,
courseName = test.Course.Name,
onDate = test.OnDate.ToShortDateString() ,
lastRegisterDate = test.LastRegisterDate
};
DataTable dtgrdSource= query.CopyToDataTable<DataRow>();
try
{
gridAllTests.DataSource =dtgrdSource;
gridAllTests.DataBind();
// DataTable dt = (DataTable)dsGrdDource.Tables[0];
Session["taskTable"] = dtgrdSource;
}
catch (Exception err)
{
lblError.Text = err.Message.ToString();
}
}
If you are using ToShortDateString() do not apply formatting at boundfield as datetime formatting can not be applied to strings .
If you do not wish to use ToShortDateString() just try above code without ToShortDateString() and use formatting at BoundField.

Related

Keeping Retrieved data in Griview from Another Gridview

The issue is I am using 2 gridviews on two different forms; the first one is to display items from a database and it working fine. When I select a row and click a button, the row will go to gridview #2 on the second form "Shopping Cart Form" I will display the row, but when I close the form or when I select another row from gridview #1 and want to retrieve it the first row that has been retrieved will be replaced by the new select row! how i can keep all the select item in gridview 2?
Here is the code for Grid View 1
private void Buyer_Main_Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-CJGIQ74;Initial Catalog=Items;Integrated Security=True");
SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM list", con);
DataTable dt = new DataTable();
adp.Fill(dt);
foreach (DataRow item in dt.Rows)
{
int n = Gridview.Rows.Add();
Gridview.Rows[n].Cells[0].Value = item[0].ToString();
Gridview.Rows[n].Cells[1].Value = item["Name"].ToString();
Gridview.Rows[n].Cells[2].Value = item["Price"].ToString();
Gridview.Rows[n].Cells[3].Value = item["Quantity"].ToString();
}
}
The code of the button to retrieve items to Gridview 2
private void button1_Click_1(object sender, EventArgs e)
{
Checkout datagrid = new Checkout(Gridview.SelectedRows[0].Cells[0].Value.ToString(),
Gridview.SelectedRows[0].Cells[1].Value.ToString(),
Gridview.SelectedRows[0].Cells[2].Value.ToString(),
Gridview.SelectedRows[0].Cells[3].Value.ToString());
datagrid.Show();
}
GridView 2 to display retrieved items
public Checkout(string ID, string name, string price , string quantity)
{
InitializeComponent();
dataGridView1.Rows.Add();
dataGridView1.Rows[0].Cells[0].Value = ID;
dataGridView1.Rows[0].Cells[1].Value = name;
dataGridView1.Rows[0].Cells[2].Value = price;
dataGridView1.Rows[0].Cells[3].Value = quantity;
}
So basically I want to keep retrieved data in grid-view 2 so the user can select what he want to purchase and checkout the selected items. Also, can anyone help me about the quantity how can I select only one it will be subtracted from inventory or stock I have
First GridView
<asp:GridView ID="gvAll" runat="server"
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" AllowPaging ="true"
OnPageIndexChanging = "OnPaging" PageSize = "10" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" onclick = "checkAll(this);"
AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" onclick = "Check_Click(this)"
AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField = "CustomerID" HeaderText = "Customer ID"
HtmlEncode = "false" />
<asp:BoundField DataField = "ContactName" HeaderText = "Contact Name"
HtmlEncode = "false" />
<asp:BoundField DataField = "City" HeaderText = "City"
HtmlEncode = "false" />
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
Secondary GridView
<asp:GridView ID="gvSelected" runat="server"
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" EmptyDataText = "No Records Selected" >
<Columns>
<asp:BoundField DataField = "CustomerID" HeaderText = "Customer ID" />
<asp:BoundField DataField = "ContactName" HeaderText = "Contact Name" />
<asp:BoundField DataField = "City" HeaderText = "City" />
</Columns>
</asp:GridView>
private void BindGridone()
{
string constr = ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
string query = " select CustomerID, ContactName, City from customers";
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
sda.Fill(dt);
gvAll.DataSource = dt;
gvAll.DataBind();
}
The GetData function simply retrieves the records for which the user has checked the checkbox, adds them to a DataTable and then saves the DataTable to ViewState
private void GetData()
{
DataTable dt;
if (ViewState["SelectedRecords"] != null)
dt = (DataTable)ViewState["SelectedRecords"];
else
dt = CreateDataTable();
CheckBox chkAll = (CheckBox)gvAll.HeaderRow
.Cells[0].FindControl("chkAll");
for (int i = 0; i < gvAll.Rows.Count; i++)
{
if (chkAll.Checked)
{
dt = AddRow(gvAll.Rows[i], dt);
}
else
{
CheckBox chk = (CheckBox)gvAll.Rows[i]
.Cells[0].FindControl("chk");
if (chk.Checked)
{
dt = AddRow(gvAll.Rows[i], dt);
}
else
{
dt = RemoveRow(gvAll.Rows[i], dt);
}
}
}
ViewState["SelectedRecords"] = dt;
}
private DataTable CreateDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("CustomerID");
dt.Columns.Add("ContactName");
dt.Columns.Add("City");
dt.AcceptChanges();
return dt;
}
private DataTable AddRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("CustomerID = '" + gvRow.Cells[1].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["CustomerID"] = gvRow.Cells[1].Text;
dt.Rows[dt.Rows.Count - 1]["ContactName"] = gvRow.Cells[2].Text;
dt.Rows[dt.Rows.Count - 1]["City"] = gvRow.Cells[3].Text;
dt.AcceptChanges();
}
return dt;
}
private DataTable RemoveRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("CustomerID = '" + gvRow.Cells[1].Text + "'");
if (dr.Length > 0)
{
dt.Rows.Remove(dr[0]);
dt.AcceptChanges();
}
return dt;
}
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
GetData();
gvAll.PageIndex = e.NewPageIndex;
BindGridone();
SetData();
}
protected void CheckBox_CheckChanged(object sender, EventArgs e)
{
GetData();
SetData();
BindGridtwo();
}
private void BindGridtwo()
{
DataTable dt = (DataTable)ViewState["SelectedRecords"];
gvSelected.DataSource = dt;
gvSelected.DataBind();
}

Date columns will not sort on Gridview filled from DataTable

I am using this example to sort GridView loaded from DataTable. I also reviewed this post - I used sajanyamaha advice by adding columns to DataTable and that's when GridView's date columns starting sorting properly with one peculiarity. I have 11 columns, first column is a selectcommand that redirects to another page. I have no boundfields or template fields, gridview is filled from datatable in code behind.
The problem is sorting and paging work fine on all columns EXCEPT the 2 Date columns. The Date columns, ReviewDue and SubmittedDate. They sort correctly but they do not retain the sort order while paging. GridView will reset to page 1 at each sort column change which causes the user to never see past page 1 when Date column is sorted. The issue I am trying to resolve and understand is why do all the other columns function correctly but the Date columns behave differently? What custom handling is needed to get date columns to behave like the other string or int columns?
I have googled plenty but I don't find anything with this oddity.
Here is my pertinent code.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["SortExpr"] = "EPRID";
ViewState["SortDir"] = " DESC";
if (blnIsAdmin == true || blnIsManager == true)
{
BindData();
}
else
{
//redirect
Response.Redirect("~/ErrorPages/AccessDenied.aspx");
}
}
}
private void BindData()
{
GridView1.DataSource = this.GetData();
GridView1.DataBind();
}
private DataTable GetData()
{
string cmdStr = "SELECT * FROM ….ORDER BY " + ViewState["SortExpr"].ToString() + " " + ViewState["SortDir"].ToString();
DataTable table = new DataTable();
table.Columns.Add("EPRID", typeof(Int32));
table.Columns.Add("FormName", typeof(String));
table.Columns.Add("Name", typeof(String));
table.Columns.Add("Completed", typeof(Boolean));
table.Columns.Add("Sup1", typeof(String));
table.Columns.Add("Sup2", typeof(String));
table.Columns.Add("Sup3", typeof(String));
table.Columns.Add("ReviewDue", typeof(DateTime));
table.Columns.Add("SubmittedDate", typeof(DateTime));
table.Columns.Add("SubmittedBy", typeof(String));
table.Columns.Add("DocID", typeof(Int32));
using (SqlConnection conn = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
cmd.CommandType = CommandType.Text;
//get all EPRs (unfiltered grid)
if (blnIsAdmin == true ")
{
cmdStr = "SELECT * FROM … ORDER BY " + ViewState["SortExpr"].ToString() + " " + ViewState["SortDir"].ToString();
using (SqlDataAdapter da = new SqlDataAdapter(cmdStr, conn))
{
da.Fill(table);
}
}
else if (blnIsManager == true)
{
cmdStr = "SELECT * FROM… WHERE user = #user …ORDER BY " + ViewState["SortExpr"].ToString() + " " + ViewState["SortDir"].ToString();
using (SqlDataAdapter da = new SqlDataAdapter(cmdStr, conn))
{
da.SelectCommand.Parameters.Add(new SqlParameter { ParameterName = "#user", Value = strCurrentUser, SqlDbType = SqlDbType.VarChar, Size = 50 });
da.Fill(table);
}
}
}
}
return table;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//go to page 1 when sorting
GridView1.PageIndex = 0;
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
ViewState["SortDir"] = " DESC";
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
ViewState["SortDir"] = " ASC";
}
ViewState["SortExpr"] = sortExpression;
}
private void SortGridView(string sortExpression, string direction)
{
ViewState["SortExpr"] = sortExpression;
ViewState["SortDir"] = direction;
//get unfiltered grid
DataTable dt = GetData();
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
//ViewState["sortDirection"] = SortDirection.Ascending;
ViewState["sortDirection"] = SortDirection.Descending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
<asp:GridView ID="GridView1" runat="server"
onselectedindexchanged="GridView1_SelectedIndexChanged"
AllowPaging="True"
AllowSorting="True"
Caption="List of awaiting or completed employee performance reviews"
PageSize="25"
onsorting="GridView1_Sorting"
onpageindexchanging="GridView1_PageIndexChanging"
CellPadding="4"
DataKeyNames="EPRID,DocID"
ForeColor="#333333" GridLines="None"
onrowcommand="GridView1_RowCommand"
onrowdatabound="GridView1_RowDataBound"
onselectedindexchanging="GridView1_SelectedIndexChanging"
CssClass="GridStyle" >
<RowStyle BackColor="#F7F6F3" ForeColor="Black" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
</Columns>
<FooterStyle Font-Bold="True" ForeColor="Black" />
<PagerStyle ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="Black" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
Solved! Part of the issue was with the SELECT statement in the view that was used in Sql query strings' FROM clause, cmdStr (details of this were left out of my original question for brevity-possibly my first error in getting proper help?). In the views' SELECT statement, the 2 datetime columns were constructed like this:
,Convert(varchar(10),NextReview,112) as ReviewDue
,Convert(varchar(10),SubmittedDate,112) as SubmittedDate
and should have been simply:
,NextReview as ReviewDue
,SubmittedDate
,etc...
(BTW it made no differnce which standard I used, 101, 110, 111, 112...). Also the corresponding data types in the DataTable's Add() method should match as DateTimein GetData(). Finally I added a condition and modified the ORDER BY clause in the SQL inline query, cmdStr to:
//pass ViewState to variable for use in cmdStr when DateTime columns are sorted on
strExpression = ViewState["SortExpr"].ToString();
if (strExpression == "ReviewDue" || strExpression == "SubmittedDate")
{
cmdStr = "SELECT * FROM vwView ORDER BY CONVERT(DATE, " + strExpression + ", 120) " + ViewState["SortDir"].ToString();
}
else
{
//use original cmdStr
}
In the gridviews _RowDataBound() event I also formated the date to show Date part only in the grid like this:
//ReviewDue will never be null
e.Row.Cells[8].Text = Convert.ToDateTime(((DataRowView)e.Row.DataItem)["ReviewDue"]).ToString("d");
//SubmittedDate can be null, handle null
object dtmDate9 = ((DataRowView)e.Row.DataItem)["SubmittedDate"];
if (dtmDate9 == DBNull.Value)
{
e.Row.Cells[9].Text = String.Empty;
}
else
{
e.Row.Cells[9].Text = Convert.ToDateTime(((DataRowView)e.Row.DataItem)["SubmittedDate"]).ToString("d");
}

how to rearrange column in gridview?

i retrieve gridview from database. but i change the structure of gridview. it different display from database which is i put the row in database become column in gridview. but the column i want for example Date|A|B|C|D but i get in gridview like this Date|B|D|A|C|. the B|D|A|C i retrieve from column prod_line in database. how to rearrange it back ? this is my code :
protected void Page_Load(object sender, EventArgs e)
{
//where request_date >= DATEADD(day,-8, GETDATE())
con.Open();
DataTable dtTemp = new DataTable();
cmd = new SqlCommand("SELECT request_date,prod_line,jo_no,qty,CONVERT(VARCHAR(10),need_by_date ,101) as need_by_date FROM CutPanelCard order by request_date", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtTemp);
con.Close();
ViewState["Information"] = dtTemp;
try
{
con.Open();
{
//DataTable dtTemp = (DataTable)ViewState["Information"];
DataTable dtDistinctRecords = dtTemp.DefaultView.ToTable(true, "prod_line");
DataTable dtStudentName = dtTemp.DefaultView.ToTable(true, "request_date");
DataTable a = new DataTable();
DataTable dtStudent = new DataTable();
dtStudent.Columns.Add("request_date");
foreach (DataRow rows in dtDistinctRecords.Rows)
{
dtStudent.Columns.Add(rows["prod_line"].ToString());
}
foreach (DataRow row in dtStudentName.Rows)
{
DataRow dr = dtStudent.NewRow();
dr["request_date"] = row["request_date"];
DataView dv = new DataView(dtTemp);
dv.RowFilter = "request_date='" + row["request_date"] + "'";
DataTable dtStudentdtl = dv.ToTable();
for (int i = 0; i < dtStudentdtl.Rows.Count; i++)
{
string colValue = dtStudentdtl.Rows[i]["jo_no"].ToString();
string colValue2 = dtStudentdtl.Rows[i]["qty"].ToString();
string colValue3 = dtStudentdtl.Rows[i]["need_by_date"].ToString();
dr[dtStudentdtl.Rows[i]["prod_line"].ToString()] = "JO: " + colValue + " Quantity: " + colValue2 + " Need by Date: " + colValue3 ;
}
dtStudent.Rows.InsertAt(dr, dtStudent.Rows.Count);
}
GridView1.DataSource = dtStudent;
GridView1.DataBind();
//GridView_Row_Merger(GridView1);
GridView_Row_Merger(GridView1);
con.Close();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
I'm guessing you are using AutoGenerated Columns. So the easiest way would be to rearrange your query. The first column you select will be the first in the GridView.
SELECT jo_no, qty, request_date, prod_line ...
That will change the order in the GridView. However I suggest you start using TemplateFields. You have much more control over the Grid layout and design.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<%# Eval("prod_line") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<%# Eval("qty") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

'ddlItem' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value

I'm getting this error whenever I try to bind data inside gridview dropdownlist.
Here is the aspx code:
<asp:TemplateField HeaderText="Item Description" SortExpression="ddlItem">
<ItemTemplate>
<asp:DropDownList ID="ddlItem" runat="server" Height="25px" Width="200px" SelectedValue='<%# Eval("ddlItem") %>'>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
Here is the code behind (c#):
private void SetInitialRowToGrid()
{
// Initialize and Set initial row of Datatable
var tempDataTable = new DataTable();
tempDataTable.Columns.Add("lblId");
tempDataTable.Columns.Add("ddlItem");
tempDataTable.Columns.Add("txtUnit");
tempDataTable.Columns.Add("txtQty");
tempDataTable.Rows.Add("1", "", "", "");
// Store that datatable into viewstate
ViewState["TempTable"] = tempDataTable;
// Attach Gridview Datasource to datatable
gvItemList.DataSource = tempDataTable;
gvItemList.DataBind(); //Here I'm getting the error.
}
protected void gvItemList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlItem = (e.Row.FindControl("ddlItem") as DropDownList);
Jilu1TableAdapters.tbl_ItemTableAdapter item;
item = new Jilu1TableAdapters.tbl_ItemTableAdapter();
DataTable dt = new DataTable();
dt = item.GetItems();
ddlItem.DataSource = dt;
ddlItem.DataTextField = "Item";
ddlItem.DataValueField = "Item";
ddlItem.DataBind();
ddlItem.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--Select an Item--", "0"));
}
}
protected void ddlSiteID_SelectedIndexChanged(object sender, EventArgs e)
{
Jilu1TableAdapters.tbl_Jr_BOMTableAdapter ds;
ds = new Jilu1TableAdapters.tbl_Jr_BOMTableAdapter();
DataTable dt = new DataTable();
dt = ds.GetVersion(ddlSiteID.SelectedValue);
ddlVersion.DataSource = dt;
ddlVersion.DataValueField = "Version";
ddlVersion.DataTextField = "Version";
ddlVersion.DataBind();
int ver = Convert.ToInt32(ddlVersion.Text);
DataTable dt1 = new DataTable();
dt1 = ds.GetDetails(ddlSiteID.SelectedValue, ver);
foreach (DataRow row in dt1.Rows)
{
txtSiteName.Text = (row["txtSiteName"].ToString());
ddlSiteType.Text = (row["ddlSiteType"].ToString());
txtNoBTS.Text = (row["txtNoBTS"].ToString());
txtNoLinks.Text = (row["txtNoLinks"].ToString());
txtLoadBand.Text = (row["txtLoadBand"].ToString());
ddlEBAvailability.Text = (row["ddlEBAvailability"].ToString());
txtEBPhase.Text = (row["txtEBPhase"].ToString());
txtDGCapacity.Text = (row["txtDGCapacity"].ToString());
txtDGPhase.Text = (row["txtDGPhase"].ToString());
}
gvItemList.DataSource = dt1;
gvItemList.DataBind();
}
I tried putting Text = 'Bind("ddlItem")', Datasourse, SelectedValue but still no luck.
Any help will be greatly appreciated.
In this code ,
<asp:DropDownList ID="ddlItem" runat="server" Height="25px" Width="200px"
SelectedValue='<%# Eval("ddlItem") %>'>
</asp:DropDownList>
you set SelectedValue to '<%# Eval("ddlItem") %>' but ddlItem is not exist in your datasource fields .
Put the correct field which you want to display in your dropdownlist .
And I suggest you to set DataTextField and DataValueField of your DropDownList .
Set it like DataTextField="ddlItem" DataValueField="ddlItem" .
Hope it's help for you :)
Your way is wrong
try this below way
protected void gvItemList_RowDataBound(object sender, GridViewEditEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList= (DropDownList)e.Row.FindControl("ddlItem");
//bind dropdownlist
DataTable dt = con.GetData("select * from tablename");//selected data from db or anywhere for bind ddl
ddList.DataSource = dt;
ddList.DataTextField = "YourCOLName";//id
ddList.DataValueField = "YourCOLName";//displaying name
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
ddList.SelectedValue = dr["YourCOLName"].ToString();// default selected value
}
}
}

Gridview inside Datalist ASP.NET

I am trying to place an asp gridview inside an asp datalist. For each item in the datalist I would like certain values from another database table to be returned.
I have written the following code, but the gridview returns not data (I can confirm there is records in the database and the stored procedure is correct). The asp datalist is working fine.
What am I doing wrong that is not populating the gridview?
<asp:DataList runat="server" id="listResponses" DataKeyField="QuestionID" CssClass="confirm" OnItemDataBound="listResponses_ItemDataBound">
<ItemTemplate>
<h3 class="confirm new">Question <asp:Label ID="lblaOrder" runat="server" Text='<%# Container.ItemIndex + 1 %>'></asp:Label></h3>
<div class="confirm_question">
<asp:Label ID="lblOrder" runat="server" Text='<%# Container.ItemIndex + 1 %>'></asp:Label>
<p class="confirm"><%# DataBinder.Eval(Container.DataItem, "QuestionText") %></p>
</div> <!-- end confirm_question -->
<asp:GridView runat="server" ID="gridResponses" DataKeyNames="QuestionID"">
<Columns>
<asp:BoundField DataField="AnswerTitle" HeaderText="ID" HeaderStyle-Width="80px" ItemStyle-CssClass="bo"></asp:BoundField>
<asp:BoundField DataField="Responses" HeaderText="Response Count" HeaderStyle-Width="150px" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:DataList>
And here is the code behind.
public partial class questionnaire_responses : System.Web.UI.Page
{
OsqarSQL GetData;
DataTable DT;
private string _productConnectionString;
private SqlConnection _productConn;
protected void Page_Load(object sender, EventArgs e)
{
string questionnaireId = Session["qID"].ToString();
int qid = Convert.ToInt32(questionnaireId);
GetData = new OsqarSQL();
string name = GetData.GetQuestionnaireName(qid);
lblQuestionnaireName.Text = name;
if (!IsPostBack)
{
DT = GetData.GetQuestionNameDataList(qid);
listResponses.DataSource = DT;
listResponses.DataBind();
}
}
private void BindGrid(GridView GridView, int questionId)
{
DataTable dt = new DataTable();
GetData.GetAnswerTitle(questionId);
GridView.DataSource = dt;
GridView.DataBind();
}
protected void listResponses_ItemDataBound(object sender, DataListItemEventArgs e)
{
GridView gridResponses=(GridView)e.Item.FindControl("gridResponses");
BindGrid(gridResponses, (int)listResponses.DataKeys[e.Item.ItemIndex]);
}
}
//Method from the data access class
public DataTable GetAnswerTitle(int QuestionId)
{
string returnValue = string.Empty;
SqlCommand myCommand = new SqlCommand("GetAnswer", _productConn);
myCommand.CommandType = CommandType.StoredProcedure;
,yCommand.Parameters.Add(new SqlParameter("#QUESTION_ID", SqlDbType.Int));
myCommand.Parameters[0].Value = QuestionId;
return createDataTable(getData(myCommand));
}
You've created an empty DataTable as DataSource for your GridView.
Replace
DataTable dt = new DataTable();
GetData.GetAnswerTitle(questionId);
GridView.DataSource = dt;
with this
DataTable dt = GetData.GetAnswerTitle(questionId);
GridView.DataSource = dt;

Categories

Resources