asp.net Gridview does not display - c#

I try to bind my list of objects to my datasource.
But as I switched from autogeneratecolums to boundfields, the whole grid is not displayed anymore.
Is there something I miss to let this work proper?
asp:
<asp:GridView ID="grid_article"
AutoGenerateColumns="false"
runat="server"
GridLines="None"
AllowPaging="true"
CssClass="mGrid"
PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt"
OnPageIndexChanging="ArticleGrid_PageIndexChanging">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="cbSelect" runat="server" ReadOnly="false"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="itemNumber" HeaderText="Product Number" ReadOnly="true"></asp:BoundField>
<asp:BoundField DataField="name" HeaderText="Product Name" ReadOnly="true"></asp:BoundField>
<asp:BoundField DataField="description" HeaderText="Product Description" ReadOnly="true"></asp:BoundField>
<asp:BoundField DataField="purchasePrice" HeaderText="Purchase Price" ReadOnly="true"></asp:BoundField>
<asp:BoundField DataField="salesPrice" HeaderText="Sales Price" ReadOnly="true"></asp:BoundField>
</Columns>
</asp:GridView>
code behind:
if (articles != null)
{
if (articles.Count != 0)
{
DataTable dt = new DataTable();
dt.Columns.Add("itemNumber");
dt.Columns.Add("name");
dt.Columns.Add("description");
dt.Columns.Add("purchasePrice");
dt.Columns.Add("salesPrice");
foreach (AccessoryDTO item in articles)
{
DataRow dr = dt.NewRow();
dr["itemNumber"] = item.itemNumber;
dr["name"] = item.name;
dr["description"] = item.description;
dr["purchasePrice"] = item.purchasePrice + " " + item.currency;
dr["salesPrice"] = item.salesPrice + " " + item.currency;
dt.Rows.Add(dr);
}
grid_article.DataSource = dt;
show_record_count(articles.Count);
grid_article.DataBind();
}
else
{
grid_article.DataSource = null;
grid_article.DataBind();
}
}

try like this code that i worked with in sharepoint 2013 :
<asp:GridView ID="OffresGrid" CssClass="dataTable" runat="server" AutoGenerateColumns="false" EmptyDataText="Pas de données." AllowPaging="True" PageSize="1000" OnPageIndexChanging="OffresGrid_PageIndexChanging" OnRowDataBound="OffresGrid_RowDataBound" >
<Columns>
<asp:TemplateField HeaderText="Secteur">
<ItemTemplate>
<asp:Label ID="Secteur" runat="server" Text='<%#Eval("Secteur") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Réference">
<ItemTemplate>
<asp:LinkButton ID="Reference" runat="server" Text='<%#Eval("Reference") %>' OnCommand="reference_Command" CommandArgument='<%#Eval("Reference") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Titre">
<ItemTemplate>
<asp:Label ID="Title" runat="server" Text='<%#Eval("Title")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date limité">
<ItemTemplate>
<asp:Label ID="DateLimite" runat="server" Text='<%#Eval("DateLimite")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date de publication">
<ItemTemplate>
<asp:Label ID="DatePublication" runat="server" Text='<%#Eval("DatePublication")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lieux">
<ItemTemplate>
<asp:Label ID="Lieux" runat="server" Text='<%#Eval("Lieux")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
C# code :
DataTable dt = new DataTable();
string Secteur, Reference, Title, DateLimite, DatePublication, Lieux;
dt.Columns.Add("Secteur", typeof(string));
dt.Columns.Add("Reference", typeof(string));
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("DateLimite", typeof(string));
dt.Columns.Add("DatePublication", typeof(string));
dt.Columns.Add("Lieux", typeof(string));
try
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Offres"];
SPListItemCollection coll = list.Items;
foreach (SPListItem item in coll)
{
if (item["Secteur"] != null)
{
Secteur = item["Secteur"].ToString();
}
else
{
Secteur = "";
}
if (item["Reference"] != null)
Reference = item["Reference"].ToString();
else
Reference = " ";
if (item["Title"] != null)
Title = item["Title"].ToString();
else
Title = " ";
if (item["DateLimite"] != null)
DateLimite = item["DateLimite"].ToString();
else
DateLimite = " ";
if (item["DatePublication"] != null)
DatePublication = item["DatePublication"].ToString();
else
DatePublication = " ";
if (item["Lieux"] != null)
Lieux = item["Lieux"].ToString();
else
Lieux = " ";
dt.Rows.Add(Secteur, Reference, Title, DateLimite,
DatePublication, Lieux);
}
OffresGrid.DataSource = dt;
OffresGrid.DataBind();
}
}
}
catch (Exception )
{
}

Related

Image is not displaying after adding items to the cart

Failed to load resource: the server responded with a status of 404 ()
System.Byte[]:1
This error is coming on inspecting it
protected void AllData()
{
if (Session["AddProduct"].ToString() == "true")
{
Session["AddProduct"] = "false";
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("ImageID");
dt.Columns.Add("ImageName");
dt.Columns.Add("ImageFile");
dt.Columns.Add("Price");
if (Request.QueryString["Id"] != null)
{
if (Session["Buyitems"] == null)
{
dr = dt.NewRow();
string cont = #"";
SqlConnection sqlcon = new SqlConnection(cont);
SqlCommand cmd = new SqlCommand();
string query = "select * from tblclothes where ImageID=" + Request.QueryString["Id"];
cmd.CommandText = query;
cmd.Connection = sqlcon;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
dr["ImageID"] = ds.Tables[0].Rows[0]["ImageID"].ToString();
dr["ImageName"] = ds.Tables[0].Rows[0]["ImageName"].ToString();
dr["ImageFile"] = ds.Tables[0].Rows[0]["ImageFile"].ToString();
dr["Price"] = ds.Tables[0].Rows[0]["Price"].ToString();
dt.Rows.Add(dr);
gvproducts.DataSource = dt;
gvproducts.DataBind();
Session["buyitems"] = dt;
}
this is the code
protected static string ReturnEncodedBase64UTF8(object rawImg)
{
string img = "data:image/jpg;base64,{0}"; //change image type if need be
string toEncodeAsBytes = rawImg.ToString();
string returnValue = System.Convert.ToString(toEncodeAsBytes);
return String.Format(img, returnValue);
}
<asp:GridView ID="gvproducts" OnRowDataBound="gvproducts_RowDataBound" ShowFooter="true" HeaderStyle-BackColor="Blue"
HeaderStyle-ForeColor="White" OnRowDeleting="gvproducts_RowDeleting" runat="server" AutoGenerateColumns="false"
EmptyDataText="No Data Available" FooterStyle-Font-Bold="true" Width="400px">
<Columns>
<%--<asp:BoundField DataField="S.No" HeaderText="S.No" />--%>
<asp:BoundField DataField="ImageId" HeaderText="Image Id" />
<asp:BoundField DataField="ImageName" HeaderText="Image Name" />
<%--<asp:ImageField DataImageUrlField="ImageFile" HeaderText="Image"></asp:ImageField>--%>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<%--<img src='../Images/ <%# Eval("ImageFile") %>' id="img" runat="server" />--%>
<asp:Image ID="img" runat="server" ImageUrl='<%# "data:Image/png;base64," + Eval("ImageFile") %>' />
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="OriginalFormat" HeaderText="Format" />--%>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblprice" runat="server" Text='<%# Eval("Price") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotalPrice" runat="server" Text="Total Price"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
Regarding you case, you need to do the following:
When getting the DataRow, you need to cast it to Byte[] and convert it to a Base64 string like this:
dr["ImageFile"] = Convert.ToBase64String((Byte[])ds.Tables[0].Rows[0]["ImageFile"]);
Once you have the Base64 string, then you can apply it to your control like this:
<img src='data:image/jpg;base64, <%# Eval("ImageFile")%>' />

How to group specific column in grid view

In Grid view I am having one field Items Group. I want to group all the Item group values together in gridview row wise with header name as Itemgroup.
Like Header Text as Itemgroup values followed by its values respectfully.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" HorizontalAlign="Center">
<Columns>
<asp:TemplateField HeaderText="Item Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("TestItemName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Items Group">
<ItemTemplate>
<asp:Label ID="lblGroup" runat="server" Text='<%# Eval("TestItemGroup") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<asp:TextBox ID="txtItemGroup" runat="server" Text='<%# Eval("ItemGroup") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lblGroup12" runat="server" Text='<%# Eval("TestItemID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Label ID="lblItemValue" runat="server" Text='<%# Eval("TestItemValues") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Default Values">
<ItemTemplate>
<asp:Label ID="lblDefaultValues" runat="server" Text='<%# Eval("DefaultValues") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Binding Grid view in .cs:
int ID = Convert.ToInt32(txtID.Text);
sqlstr = "select * from Test_Items where TestID = '" + ID + "'";
SqlDataAdapter da = new SqlDataAdapter(sqlstr, con);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds != null && ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
btnSend1.Visible = true;
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "", "alert('Invalid ID (or) No Data to Display..!');", true);
}
For Better understanding Ex:
http://www.pathology-software.com/images/pathology-software/patholgy-screenshot7.jpg
Thank you in Advance
You can inject the needed separator rows by adding “separator records” to the data source before binding it to the GridView.
Here is an example I came across:
protected override void Render(HtmlTextWriter writer)
{
string lastSubCategory = String.Empty;
Table gridTable = (Table)gvProducts.Controls[0];
foreach (GridViewRow gvr in gvProducts.Rows)
{
HiddenField hfSubCategory = gvr.FindControl("hfSubCategory") as
HiddenField;
string currSubCategory = hfSubCategory.Value;
if (lastSubCategory.CompareTo(currSubCategory) != 0)
{
int rowIndex = gridTable.Rows.GetRowIndex(gvr);
// Add new group header row
GridViewRow headerRow = new GridViewRow(rowIndex, rowIndex,
DataControlRowType.DataRow, DataControlRowState.Normal);
TableCell headerCell = new TableCell();
headerCell.ColumnSpan = gvProducts.Columns.Count;
headerCell.Text = string.Format("{0}:{1}", "SubCategory",
currSubCategory);
headerCell.CssClass = "GroupHeaderRowStyle";
// Add header Cell to header Row, and header Row to gridTable
headerRow.Cells.Add(headerCell);
gridTable.Controls.AddAt(rowIndex, headerRow);
// Update lastValue
lastSubCategory = currSubCategory;
}
}
base.Render(writer);
}
FULL ARTICLE
<asp:Literal ID="litDataLoader" runat="server">
</asp:Literal>
<asp:GridView ID="gvTemp" runat="server" AutoGenerateColumns="false" BorderWidth="0" ShowHeader="false" ShowFooter="false">
<Columns>
<asp:TemplateField ControlStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblTestItemName" runat="server" Text='<%#Eval("TestItemName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ControlStyle-Width="220px">
<ItemTemplate>
<asp:Label ID="lblTestItemValues" runat="server" Text='<%#Eval("Itm") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ControlStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblDefaultValues" runat="server" Text='<%#Eval("DefaultValues") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Binding Grid view in .cs:
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
private void bindData()
{
string Query = "select TestItemID,TestItemName,TestItemValues,DefaultValues,TestID,ItemGroup,isnull(TestItemGroup,'-') as TestItemGroup, (ItemGroup + ' ' + TestItemValues) as Itm from Test_Items where TestID = '" + ViewState["id"].ToString() + "'";
SqlDataAdapter da = new SqlDataAdapter(Query, con);
DataTable dt = new DataTable();
da.Fill(dt);
var rows = dt.AsEnumerable().Select(s => new { id = s.Field<string>("TestItemGroup"), }).Distinct().ToList();
int count = rows.Count;
if (dt.Rows.Count > 0)
{
StringBuilder build = new StringBuilder();
foreach (var row in rows)
{
string Name = row.id != "-" ? row.id : " ";
build.Append("<b>" + Name + "</b>");
DataTable dts = new DataTable();
dts = dt.Select("TestItemGroup = '" + row.id + "'").CopyToDataTable();
gvTemp.Visible = true;
gvTemp.DataSource = dts;
gvTemp.DataBind();
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvTemp.RenderControl(hw);
string gridHTML = sw.ToString().Replace("\"", "'").Replace(System.Environment.NewLine, "");
build.Append(gridHTML);
gvTemp.Visible = false;
}
litDataLoader.Text = build.ToString();
}
}

loading vertical columns in grid with data's coming from database

I wanted to load the grid columns vertically with data's coming from database.Please someone help me.I wanted to further edit in the gridcolumn. below is my code
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" Width="95%" style="text-align:center;" GridLines="Both"
AutoGenerateColumns="false" DataKeyNames="WORKSHEET_ID" HeaderStyle-ForeColor="White" onrowediting="EditTaskStatus" onrowupdating="UpdateTaskStatus" onrowcancelingedit="CancelTaskStatus"
AllowPaging ="true" emptydatatext="No Approval Task" OnPageIndexChanging = "OnPaging" BackColor="AliceBlue" Font-Size = "11pt" AlternatingRowStyle-BackColor = "#F2F2F2" RowStyle-BorderWidth="1" AlternatingRowStyle-BorderWidth="1"
HeaderStyle-BackColor = "#00829c" HeaderStyle-BorderColor="#CC9966" PagerStyle-CssClass="pagenation" HeaderStyle-BorderWidth="1px" HeaderStyle-BorderStyle="Solid" EditRowStyle-Wrap="true"
PageSize = "5">
<Columns>
<asp:TemplateField Visible="false" ItemStyle-Width = "30px" HeaderText = "Id">
<ItemTemplate>
<asp:Label ID="lblid" runat="server"
Text='<%# Eval("WORKSHEET_ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "50px" HeaderText ="Total Hours">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server"
Text='<%# Eval("TOTAL_HOURS")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Final Status" ItemStyle-Width = "50px">
<ItemTemplate>
<asp:Label ID="lblFinalStatus" runat="server" Text='<%# Eval("MGR_STATUS") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="ddlTaskStatus">
<asp:ListItem Text="Accept" Value="1"></asp:ListItem>
<asp:ListItem Text="Decline" Value="2"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText ="Comments">
<EditItemTemplate>
<asp:TextBox ID="txtComments" runat="server"
Text='<%# Eval("MGR_COMMENTS") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" ItemStyle-Width = "50px">
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" runat="server" CommandName="Edit" ImageUrl="~/images/edit.gif" Width="16" Height="16" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" runat="server" CommandName="Update" ImageUrl="~/images/action_check.gif" Width="16" Height="16" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/images/action_delete.gif" Width="16" Height="16" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Please help me in the backend i have given the code as
protected void BindGridviewData()
{
DataTable dt = new DataTable();
string strQuery = "SELECT * from Master_Worksheets where MGR_CODE ='" + lblUsername.Text + "' AND (MGR_STATUS='New' OR MGR_STATUS='Decline')";
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand(strQuery);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
gvconverted.DataSource = ConvertColumnsAsRows(dt);
gvconverted.DataBind();
gvconverted.HeaderRow.Visible = false;
}
public DataTable ConvertColumnsAsRows(DataTable dt)
{
DataTable dtnew = new DataTable();
//Convert all the rows to columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
dtnew.Columns.Add(Convert.ToString(i));
}
DataRow dr;
// Convert All the Columns to Rows
for (int j = 0; j < dt.Columns.Count; j++)
{
dr = dtnew.NewRow();
dr[0] = dt.Columns[j].ToString();
for (int k = 1; k <= dt.Rows.Count; k++)
dr[k] = dt.Rows[k - 1][j];
dtnew.Rows.Add(dr);
}
return dtnew;
}
I guess you need to swap the rows and columns of Datatable.
If that is what you need then please refer this link. It will help you
http://www.codeproject.com/Articles/44274/Transpose-a-DataTable-using-C

Hiding GridView Columns with ItemTemplate

I Have a GridView in .aspx page that I want to hide columns based on aspx.cs BindData() method. I have tried using below code but not able to hide. I am using Asp.net with C#.
Below is my GridView with columns and I have also included the Button click code.
<GridView>
<Columns>
<asp:BoundField DataField="id" HeaderText="Id" SortExpression="id"
Visible="false" />
<asp:TemplateField HeaderText="RollNo" >
<ItemTemplate>
<%# Eval("st_rollno")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbsturollno" runat="Server"
Text='<%# Eval("st_rollno") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("st_name")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbstuname" runat="Server"
Text='<%# Eval("st_name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Theory">
<ItemTemplate>
<%# Eval("theory")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtheory" runat="Server"
Text='<%# Eval("theory") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" >
<ItemTemplate>
<%# Eval("ttotal")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtheorytotal" runat="Server"
Text='<%# Eval("ttotal") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lab" >
<ItemTemplate>
<%# Eval("lab")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tblab" runat="Server"
Text='<%# Eval("lab") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" >
<ItemTemplate>
<%# Eval("ltotal")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tblabtotal" runat="Server"
Text='<%# Eval("ltotal") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tutorial" >
<ItemTemplate>
<%# Eval("tutorial")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtutorial" runat="Server"
Text='<%# Eval("tutorial") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" >
<ItemTemplate>
<%# Eval("tutotal")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtutorialtotal" runat="Server"
Text='<%# Eval("tutotal") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</GridView>
private void BindData()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
if (stype.Equals("L"))
{
query = "SELECT [id], [st_rollno], [st_name], [lab], [ltotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
GridView1.Columns[3].Visible = false;
GridView1.Columns[4].Visible = false;
GridView1.Columns[7].Visible = false;
GridView1.Columns[8].Visible = false;
}
else if (stype.Equals("T"))
{
query = "SELECT [id], [st_rollno], [st_name], [theory], [ttotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
GridView1.Columns[5].Visible = false;
GridView1.Columns[6].Visible = false;
GridView1.Columns[7].Visible = false;
GridView1.Columns[8].Visible = false;
}
else if (stype.Equals("T-L"))
{
GridView1.Columns[7].Visible = false;
GridView1.Columns[8].Visible = false;
query = "SELECT [id], [st_rollno], [st_name], [theory], [ttotal], [lab], [ltotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
}
else
{
query = "SELECT [id], [st_rollno], [st_name],[theory], [ttotal], [lab], [ltotal], [tutorial], [tutotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
}
com = new SqlCommand(query);
com.Parameters.Add("#branch_name", dept);
com.Parameters.Add("#scode", dpsubject.SelectedItem.Text.ToString());
com.Parameters.Add("#sem_no", Int32.Parse(dpsemno.SelectedItem.Text.ToString()));
com.Parameters.Add("#sess_no",Int32.Parse(dpsessional.SelectedItem.Text.ToString()));
using (SqlDataAdapter sda = new SqlDataAdapter())
{
com.Connection = con;
con.Open();
sda.SelectCommand = com;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
}
}
protected void bsubmit_Click(object sender, EventArgs e)
{
this.BindData();
}
<asp:GridView runat="server" ID="GridView1"
AutoGenerateColumns="False" OnPreRender="GridView_PreRender">
<Columns>
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var users = new List<User>
{
new User {FirstName = "John", LastName = "Doe"},
new User {FirstName = "Marry", LastName = "Newton"},
new User {FirstName = "Joe", LastName = "Black"}
};
GridView1.DataSource = users;
GridView1.DataBind();
}
}
protected void GridView_PreRender(object sender, EventArgs e)
{
foreach (DataControlField column in GridView1.Columns)
if (column.HeaderText == "FirstName")
column.Visible = false;
}
With the GrideView.DataBind() you're calling a PostBack that will undo any changed you've made to the front end. Try doing the work on the columns after the DataBind.

Gridview bound to datatable edit dropdownlist C#

I have a GridView that is bound to a DataTable, and when you select edit, I can get the values to change. However, one field needs to be a dropdownlist and not a textbox. Here's the code I have so far.
protected void griditems_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DataTable dt = (DataTable)Session["table"];
//Update the values.
GridViewRow row = griditems.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Part"] = ((TextBox)(row.Cells[1].Controls[0])).Text.ToUpper();
dt.Rows[row.DataItemIndex]["Quantity"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Ship-To"] = ((TextBox)(row.Cells[3].Controls[0])).Text.ToUpper();
dt.Rows[row.DataItemIndex]["Requested Date"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
//dt.Rows[row.DataItemIndex]["Shipping Method"] = ((TextBox)(row.Cells[5].Controls[0])).Text;
DropDownList cmbType = (DropDownList)griditems.Rows[e.RowIndex].FindControl("Shipping Method");
griditems.EditIndex = -1;
BindData();
}
}
When I uncomment the line for the shipping method to be a textbox, it does just as it says, a textbox, not a dropdownlist. I have tried changing it to a DropDownList with no luck.
In the aspx file:
<asp:GridView ID="griditems" runat="server"
onrowdeleting="griditems_RowDeleting" onrowediting="griditems_RowEditing"
onrowupdating="griditems_RowUpdating" AllowPaging="True" onpageindexchanging="griditems_PageIndexChanging"
onrowcancelingedit="griditems_RowCancelingEdit" ViewStateMode="Enabled" Caption="Order Details"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True"
onrowdatabound="griditems_RowDataBound" >
<EditRowStyle BackColor="#FF9900" BorderStyle="Double" /></asp:GridView>
and when the table is generated:
public void CreateTable()
{
DataTable table = new DataTable();
if (Session["table"] != null)
table = (DataTable)Session["table"];
else
{
table.Columns.Add("Part", typeof(string));
table.Columns.Add("Quantity", typeof(Int32));
table.Columns.Add("Ship-To", typeof(string));
table.Columns.Add("Requested Date", typeof(string));
table.Columns.Add("Shipping Method", typeof(string));
}
DataRow row = table.NewRow();
row["Part"] = part;
row["Quantity"] = qty;
row["Ship-To"] = shipto;
row["Requested Date"] = reqdate;
row["Shipping Method"] = shipmthd;
table.Rows.Add(row);
Session["table"] = table;
griditems.DataSource = table.DefaultView;
griditems.DataBind();
}
Try dis:
Default.aspx: (Best practise use Template Field in GridView)
<asp:GridView ID="gvshipping" runat="server" AutoGenerateColumns="False"
onrowcancelingedit="gvshipping_RowCancelingEdit"
onrowdatabound="gvshipping_RowDataBound"
onrowediting="gvshipping_RowEditing" CellPadding="4" ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Part">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("part") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" Text='<%# Bind("part") %>' runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quatity">
<ItemTemplate>
<asp:Label ID="lblqty" runat="server" Text='<%# Bind("quantity") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtqty" runat="server" Text='<%# Bind("quantity") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ship to">
<ItemTemplate>
<asp:Label ID="lblshipto" runat="server" Text='<%# Bind("ShipTo") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtshipto" runat="server" Text='<%# Bind("ShipTo") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Post date">
<ItemTemplate>
<asp:Label ID="lblpostdate" runat="server" Text='<%# Bind("RequestedDate")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtpostdate" Text='<%# Bind("RequestedDate")%>' runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shipping Method">
<ItemTemplate>
<asp:Label ID="lblshipmethod" runat="server" Text='<%# Bind("ShippingMethod")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
gvBind();
}
}
public void gvBind()
{
DataTable dt = createTable();
Session["tb"] = dt;
gvshipping.DataSource = Session["tb"];
gvshipping.DataBind();
}
protected void gvshipping_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList dpshipmethod = (DropDownList)e.Row.FindControl("DropDownList1");
//bind dropdownlist
DataTable dt = shipingmethodTable();
dpshipmethod.DataSource = dt;
dpshipmethod.DataTextField = "ShippingMethod";
dpshipmethod.DataValueField = "Id";
dpshipmethod.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
dpshipmethod.SelectedItem.Text = dr["ShippingMethod"].ToString();
}
}
}
protected void gvshipping_RowEditing(object sender, GridViewEditEventArgs e)
{
gvshipping.EditIndex = e.NewEditIndex;
vBind();
}
protected void gvshipping_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvshipping.EditIndex = -1;
gvBind();
}
public DataTable createTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("Part", typeof(string));
dt.Columns.Add("Quantity", typeof(Int32));
dt.Columns.Add("ShipTo", typeof(string));
dt.Columns.Add("RequestedDate", typeof(string));
dt.Columns.Add("ShippingMethod", typeof(string));
string date= DateTime.Now.ToShortDateString();
DataRow row = dt.NewRow();
row["Part"] = "Anchor";
row["Quantity"] = "10";
row["ShipTo"] = "blah";
row["RequestedDate"] = date;
row["ShippingMethod"] = "Charge by subtotal";
dt.Rows.Add(row);
DataRow row1 = dt.NewRow();
row1["Part"] = "blade";
row1["Quantity"] = "88";
row1["ShipTo"] = "blah";
row1["RequestedDate"] = date;
row1["ShippingMethod"] = "Charge by quantity";
dt.Rows.Add(row1);
DataRow row2 = dt.NewRow();
row2["Part"] = "cabin";
row2["Quantity"] = "4";
row2["ShipTo"] = "blah";
row2["RequestedDate"] = date;
row2["ShippingMethod"] = "Charge by subtotal";
dt.Rows.Add(row2);
DataRow row3 = dt.NewRow();
row3["Part"] = "cockpit";
row3["Quantity"] = "11";
row3["ShipTo"] = "blah";
row3["RequestedDate"] = date;
row3["ShippingMethod"] = "Charge by weight";
dt.Rows.Add(row3);
DataRow row4 = dt.NewRow();
row4["Part"] = "jack";
row4["Quantity"] = "45";
row4["ShipTo"] = "blah";
row4["RequestedDate"] = date;
row4["ShippingMethod"] = "Charge by weight";
dt.Rows.Add(row4);
DataRow row5 = dt.NewRow();
row5["Part"] = "cabin";
row5["Quantity"] = "67";
row5["ShipTo"] = "blah";
row5["RequestedDate"] = date;
row5["ShippingMethod"] = "Charge by weight";
dt.Rows.Add(row5);
DataRow row6 = dt.NewRow();
row6["Part"] = "blade";
row6["Quantity"] = "4";
row6["ShipTo"] = "blah";
row6["RequestedDate"] = date;
row6["ShippingMethod"] = "Charge by weight";
dt.Rows.Add(row6);
return dt;
}
public DataTable shipingmethodTable()
{
DataTable dtshipingmethod = new DataTable();
dtshipingmethod.Columns.Add("Id", typeof(Int32));
dtshipingmethod.Columns.Add("ShippingMethod", typeof(string));
DataRow row = dtshipingmethod.NewRow();
row["Id"] = 1;
row["ShippingMethod"] = "Charge by subtotal";
dtshipingmethod.Rows.Add(row);
DataRow row1 = dtshipingmethod.NewRow();
row1["Id"] = 2;
row1["ShippingMethod"] = "Charge by weight";
dtshipingmethod.Rows.Add(row1);
DataRow row2 = dtshipingmethod.NewRow();
row2["Id"] = 3;
row2["ShippingMethod"] = "Charge by quantity";
dtshipingmethod.Rows.Add(row2);
return dtshipingmethod;
}
ScreenShot:
you can go ahead with the help of this:
dt.Rows[row.DataItemIndex]["Shipping Method"] = ((DropDownList)row.FindControl("DropdownList1")).SelectedItem;
EDIT:
dt.Rows[row.DataItemIndex]["Shipping Method"] = ((DropDownList)
(row.Cells[5].Controls[0])).SelectedItem.ToString();

Categories

Resources