Image Not getting binded in gridview from database - c#

Following is my code... I am trying to store image in database. I have used varbinary(MAX) datatype for storing data bytes in database. Please tell me where I am going wrong.
int qtype = Convert.ToInt32(ddl_q_Type.SelectedValue);
var getQ = (from q in obj.QuestionRegistrations
orderby q.QueCode ascending
where q.QueQuesType == qtype && q.QueLanguageCode == 1
select new { q.QueCode, q.QueQuestion }
).ToArray();
index = Convert.ToInt32(ViewState["index"].ToString()) + 1;
ViewState["index"] = index;
previosIndex = index - 1;
ViewState["previosIndex"] = previosIndex;
txt_question.Text = getQ[index].QueQuestion;
lblqcode.Text = getQ[index].QueCode.ToString();
int qcode = Convert.ToInt32(lblqcode.Text);
var options = (from opt in obj.QuestionAndOptionsMappings
where opt.QueMapQuestionCode == qcode
select new { opt.QueMapOptions, opt.QueMapCorrectAnswer, opt.QueMapId, opt.QueMapImage }
).ToList();
DataTable dt = new DataTable();
dt.Columns.Add("QueMapOptions", typeof(string));
dt.Columns.Add("QueMapId", typeof(string));
dt.Columns.Add("QueMapImage", typeof(string));
foreach (var y in options)
{
DataRow dr = dt.NewRow();
dr["QueMapOptions"] = y.QueMapOptions;
dr["QueMapId"] = y.QueMapId;
dr["QueMapImage"] = (Byte[])y.QueMapImage;
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
This code for storing the image in databse
for (int i = 0; i < GridView1.Rows.Count; i++)
{
FileUpload fp = (FileUpload)GridView1.Rows[i].Cells[2].FindControl("fp");
Label lblmapid = (Label)GridView1.Rows[i].Cells[1].FindControl("lblmapid");
bool e1 = fp.HasFile;
int mapiidd = Convert.ToInt32(lblmapid.Text);
if (fp.HasFile)
{
string path = Server.MapPath("~/Uploads/") + fp.FileName;
fp.SaveAs(path);
byte[] imageBytes =
File.ReadAllBytes(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/") + fp.FileName);
int qcodelbl = Convert.ToInt32(lblqcode.Text);
QuestionAndOptionsMapping qmap = new QuestionAndOptionsMapping();
var update = obj.QuestionAndOptionsMappings.Where(q => q.QueMapId == mapiidd && q.QueMapQuestionCode == qcodelbl)
;
update.SingleOrDefault().QueMapImage = imageBytes;
obj.SaveChanges();
}
}
ASPX code
<asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="OPTIONS" HeaderStyle-Width="55%">
<ItemTemplate>
<asp:TextBox ID="Option" runat="server" Text='<%#Eval("QueMapOptions") %>' Height="40px"
Width="500px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub Section" HeaderStyle-Width="15%" Visible="false">
<ItemTemplate>
<asp:Label ID="lblmapid" runat="server" Text='<%#Eval("QueMapId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub Section" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:CheckBox ID="Chk_correct_Ans" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub Section" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:FileUpload ID="fp" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub Section" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("QueMapImage") %>' Height="80px"
Width="100px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Ok, you can't just bind a binary column to a GridView column. you need to make use of Response.BinaryWrite method.
Here are few steps to follow to achieve what you want
Create a generic handler to read binary data. We'll call it ImageHandler.ashx. Make sure you have the primary key of the table to be passed to this handler. Write the handler code something like below (just an example).
public void ProcessRequest (HttpContext context)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select [Content] from Images where ID =#ID";
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
SqlParameter ImageID = new SqlParameter("#ID", SqlDbType.BigInt);
ImageID.Value = context.Request.QueryString["ID"];
cmd.Parameters.Add(ImageID);
conn.Open();
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
context.Response.BinaryWrite((byte[])dReader["Content"]);
dReader.Close();
conn.Close();
}
And call the handler like this.
ImageUrl='<%# "ImageHandler.ashx?ID=" + Eval("ID")%>'
instead of
ImageUrl='<%#Eval("QueMapImage") %>'
Here's a complete example from where I extracted above examples.
All the best!

Related

Filtering on asp gridview headers using dropdowns on multiple columns

So I tried to added multiple filters for the gridview and I populated the dropdowns with the distinct datas of the column, but it gives me an exception, System.ArgumentException: Parameter 'siteValue' not found in the collection. I've added the mysql stored procedure along with the below code.
<asp:GridView ID="gdvTM" runat="server" AutoGenerateColumns="False" AllowPaging="true" OnPageIndexChanging="gdvTM_PageIndexChanging" DataKeyNames="ID" PageSize="10" CssClass="cssgridview" AlternatingRowStyle-BackColor="#d5d8dc" >
<Columns >
<asp:TemplateField HeaderText="Agent login">
<ItemTemplate>
<asp:Label ID="lbllogin" runat="server" Text='<%# Eval("agentlogin") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<HeaderTemplate>
Site:
<asp:DropDownList ID="ddlgvsite" runat="server" OnSelectedIndexChanged="DropDownChange" AutoPostBack="true" AppendDataBoundItems="true">
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblsite" runat="server" Text='<%# Eval("site") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Skill:
<asp:DropDownList ID="ddlgvskill" runat="server" OnSelectedIndexChanged="DropDownChange" AutoPostBack="true" AppendDataBoundItems="true">
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblskill" runat="server" Text='<%# Eval("skill") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shift">
<ItemTemplate>
<asp:Label ID="lblshift" runat="server" Text='<%# Eval("shift") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TM">
<ItemTemplate>
<asp:Label ID="lbltm" runat="server" Text='<%# Eval("tm") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GrpM">
<ItemTemplate>
<asp:Label ID="lblGrpM" runat="server" Text='<%# Eval("grpM") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OpsM">
<ItemTemplate>
<asp:Label ID="lblOpsM" runat="server" Text='<%# Eval("opsM") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Leave type">
<ItemTemplate>
<asp:Label ID="lbltype" runat="server" Text='<%# Eval("leavetype") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate >
<asp:Label ID="lbldate" runat="server" Text='<%# Eval("date", "{0:dd/MM/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Time">
<ItemTemplate>
<asp:Label ID="lbltime" runat="server" Text='<%# Eval("time") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reason" ControlStyle-Width="300px">
<ItemTemplate>
<asp:Label ID="lblreason" runat="server" Text='<%# Eval("reason") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Below would be the server side codes
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindDropDownList()
{
TableCell cells = gdvTM.HeaderRow.Cells[0];
PopulateDropDown((cells.FindControl("ddlgvsite") as DropDownList), (cells.FindControl("lblsite") as Label).Text);
PopulateDropDown((cells.FindControl("ddlgvskill") as DropDownList), (cells.FindControl("lblskill") as Label).Text);
}
private void PopulateDropDown(DropDownList ddl, string columnName)
{
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("GetApprovedData");
cmd.CommandType = CommandType.StoredProcedure;
if (ViewState["Site"] != null && ViewState["Site"].ToString() != "0")
{
cmd.Parameters.AddWithValue("#siteValue", ViewState["Site"].ToString());
}
if (ViewState["Skill"] != null && ViewState["Skill"].ToString() != "0")
{
cmd.Parameters.AddWithValue("#skillValue", ViewState["Skill"].ToString());
}
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
gdvTM.DataBind();
this.BindDropDownList();
TableCell cell = gdvTM.HeaderRow.Cells[0];
setDropdownselectedItem(ViewState["Site"] != null ? (string)ViewState["Site"] : string.Empty, cell.FindControl("ddlgvsite") as DropDownList);
setDropdownselectedItem(ViewState["Skill"] != null ? (string)ViewState["Skill"] : string.Empty, cell.FindControl("ddlgvskill") as DropDownList);
}
private void setDropdownselectedItem(string selectedvalue, DropDownList ddl)
{
if (!string.IsNullOrEmpty(selectedvalue))
{
ddl.Items.FindByValue(selectedvalue).Selected = true;
}
}
protected void DropDownChange(object sender, EventArgs e)
{
DropDownList dropdown = (DropDownList)sender;
string selectedValue = dropdown.SelectedItem.Value;
switch (dropdown.ID.ToLower())
{
case "ddlgvsite":
ViewState["Site"] = selectedValue;
break;
case "ddlgvskill":
ViewState["Skill"] = selectedValue;
break;
}
this.BindGrid();
}
private DataTable BindDropDown(string columnName)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlCommand cmd = new MySqlCommand("SELECT DISTINCT " + columnName + " FROM approved WHERE " + columnName + " IS NOT NULL", con);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
protected void gdvTM_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gdvTM.PageIndex = e.NewPageIndex;
this.BindGrid();
}
Below would be the MySql stored procedure
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetApprovedData`
(in siteValue varchar(45), in skillValue varchar(100))
BEGIN
select *
from approved
where site = siteValue or siteValue is null and
skill = skillValue or skillValue is null;
END
Please let me know what I'm doing wrong. Thanks in advance....
1) You have to changes your stored procedure like
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetApprovedData`(in siteValue varchar(45),
in skillValue varchar(100))
BEGIN
IF siteValue IS NULL and skillValue IS NULL THEN
select * from approved;
ELSEIF siteValue IS NULL and skillValue IS NOT NULL THEN
select * from approved where skill = skillValue;
ELSEIF siteValue IS NOT NULL and skillValue IS NULL THEN
select * from approved where site = siteValue;
ELSE
select * from approved where site = siteValue and skill = skillValue;
END IF;
END
2) In your BindGrid function make the changes below
private void BindGrid()
{
//Your rest of code is same here
string siteValue = null;
string skillValue = null;
if (ViewState["Site"] != null && ViewState["Site"].ToString() != "0")
{
siteValue = ViewState["Site"].ToString();
}
if (ViewState["Skill"] != null && ViewState["Skill"].ToString() != "0")
{
skillValue = ViewState["Skill"].ToString();
}
cmd.Parameters.AddWithValue("siteValue", siteValue);
cmd.Parameters.AddWithValue("skillValue", skillValue);
//Your rest of code is same here
}

Unable to get second Checkbox onwards status in gridview in asp.net c#

I am adding Select Checkbox at every row in GridView while loading from database. Below is my aspx page code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Width="100%" onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdatabound="GridView1_RowDataBound" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="cbSelect" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblid" runat="server" Text='<%# Eval("ID") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Part Number">
<ItemTemplate>
<asp:Label ID="lblpn" runat="server" Text='<%# Eval("PartNumber") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Part Desc">
<ItemTemplate>
<asp:Label ID="lblpd" runat="server" Text='<%# Eval("PartDesc") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I want to read the data from the rows which are selected in the respective Checkbox.
For this I have done following code in Button Click:
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow dr = GridView1.Rows[i];
Label lblID = (Label)dr.FindControl("lblid");
ID = Convert.ToInt32(lblID.Text);
CheckBox checkBox = (CheckBox)dr.FindControl("cbSelect");
if (checkBox.Checked)
{
}
}
Now if I select single row in grid then I am able to get the checkbox status Checked for that particular row.
But If I select multiple rows then I am getting only first selected row's checkbox status as checked.
From second row I am getting Check status as Unchecked. But I am able to get correct value in lblID label control.
Following is my function to fill gridview:
public void showgrid(string Location)
{
DataTable dt = new DataTable();
con.Open();
string strQuery = "";
SqlDataAdapter sda = new SqlDataAdapter();
if (chkConsiderPart.Checked)
strQuery = "select * from InventoryDetails where Status='Stocked' and ToLocation='" + Location + "' and PartNumber='" + ddlPartNumber.SelectedItem.Text + "'";
else
strQuery = "select * from InventoryDetails where Status='Stocked' and ToLocation='" + Location + "'";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
if (dt.Rows.Count == 0)
{
lblRowsStatus.Text = "No Records found for the selection.";
}
else
{
lblRowsStatus.Text = "There are " + dt.Rows.Count.ToString() + " Records found for the selection.";
}
}
I am only calling it in:
if (!IsPostBack)
{
showgrid(ddlFromLocation.SelectedItem.Text);
}
Also there was post-back at certain events of other controls. but even if I removed them same issue is happening.
Note: There is no code written in any of Gridview Events.

How can I render a empty grid view with Boolean table row in database?

Morning everyone, I'm a newbie of c#.
The code below
<asp:LinkButton ID="insert_new_user" runat="server" OnClick="insert_new_user_Click"
CommandName="insertnewuser" Text="add new user" BorderColor="#000099">
</asp:LinkButton>
<asp:TemplateField HeaderText="Resign?" SortExpression="BS_DEPT">
<ItemTemplate>
<asp:CheckBox ID="cb_isleave" runat="server" Checked='<%# Eval("BS_LEAVE") %>'
Visible="True" Enabled="False" ForeColor="#ff0000" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="ed_cb_isleave" runat="server" Checked='<%#Eval("BS_LEAVE") %>'
Visible="True" Enabled="true" ForeColor="#ff0000" />
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="ft_cb_isleave" runat="server" Checked="false"
Visible="True" Enabled="true" />
</FooterTemplate>
</asp:TemplateField>
When the database is empty I use these code to render a empty footer row and header
protected void insert_new_user_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
string fakequery_user = "SELECT TOP 1 [A].[BS_ID],[A].[BS_NAME_CHT],[BS_NAME_ENG] = ISNULL([A].[BS_NAME_ENG], '-'),[BS_LEAVE]=ISNULL([A].[BS_LEAVE],0),[B].[BS_NAME]" +
"FROM[BS_USER][A] LEFT OUTER JOIN[BS_DEPT][B] ON[A].[BS_DEPT] = [B].[BS_ID]";
SqlCommand fakequery = new SqlCommand(fakequery_user, conn);
conn.Open();
SqlDataAdapter da1 = new SqlDataAdapter(fakequery);
SqlDataReader dr = fakequery.ExecuteReader();
if (dr.HasRows)
{
DataTable FinalUserData = this.Bulid_UserTB();
conn.Close();
conn.Open();
da1.Fill(FinalUserData);
DataSet datasetfinaluserdata = new DataSet();
datasetfinaluserdata.Tables.Add(FinalUserData);
conn.Close();
da1.Dispose();
USER_TABLE.DataSource = datasetfinaluserdata;
USER_TABLE.DataBind();
USER_TABLE.Rows[0].Visible = false;
}
else
{
if (USER_TABLE.Rows.Count == 0)
{
renderEmptyGridView(USER_TABLE, "BS_ID, BS_NAME_CHT, BS_NAME_ENG, BS_NAME, BS_INSERTOR, BS_INSERT_TIME, BS_EDITOR, BS_EDIT_TIME, BS_LEAVE");
}
}
}
}
public static void renderEmptyGridView(GridView EmptyGridView, string FieldNames)
{
DataTable dTable = new DataTable();
char[] delimiterChars = { ',' };
string[] colName = FieldNames.Split(delimiterChars);
foreach (string myCol in colName)
{
DataColumn dColumn = new DataColumn(myCol.Trim());
dTable.Columns.Add(dColumn);
}
DataRow dRow = dTable.NewRow();
foreach (string myCol in colName)
{
dRow[myCol.Trim()] = DBNull.Value;
}
dTable.Rows.Add(dRow);
EmptyGridView.DataSourceID = null;
EmptyGridView.DataSource = dTable;
EmptyGridView.DataBind();
EmptyGridView.Rows[0].Visible = false;
}
but when I run the web, the error pop up said, "Specified cast is not valid."
I think is it the foreach() is string but in the database the "BS_LEAVE" is a Boolean?
How can I solve it ? Thank You

Dynamically adding rows to the Gridview in ASP.NET(C#)

<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="FileName">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="" Text=""></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
aspx.cs file
SqlCommand comm = new SqlCommand(Select
FileUpload.FileName AS FileName,
FileUpload.FilePath AS PATH,
SubjectMaster.SubjectName AS Subject,
MemberPersonalInformation.FirstName As SharedBy
from FileUpload",conn)
I need to print FileName(As Hyperlink),SharedBy,Subject in the Grid how can I do that?
I need to do something like this...But below approach not working
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
int i = 0;
while (rdr.Read())
{
string fip = rdr["PATH"].ToString();
HyperLink h1 = (HyperLink)GridView1.Rows[i].Cells[0].FindControl("Hyperlink1");
h1.Text = rdr["FileName"].ToString();
h1.NavigateUrl = "download.aspx?filepath=" + fip;
GridView1.Rows[i].Cells[1].Text = rdr["SharedBy"].ToString();
GridView1.Rows[i].Cells[2].Text = rdr["Subject"].ToString();
GridView1.Rows[i].Cells[3].Text = rdr["PATH"].ToString();
//GridView1.Rows[i].Rows.Add(di);
i++;
}
Try this:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="FileName">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#Eval("PATH")%>' Text='<%#Eval("FileName")%>'></asp:HyperLink>,
<asp:Literal ID="Literal1" runat="server" Text='<%#Eval("SharedBy")+", "+ Eval("Subject")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
/asp:GridView>
In the cs you can bind the grid view with your query like this:
conn.Open();
SqlCommand comm = new SqlCommand("your query");
SqlDataReader rdr = comm.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = rdr;
GridView1.DataBind();
rdr.close();

how to sort in gridview using template fields

The sorting works fine when u fill the gridview using SQL datasource in the aspx page...
but now i am using template field and the columns are filled separately in the codebehind and the sorting is not working...
my code is
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False"
ondatabound="GridView1_DataBound"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="File Name" ItemStyle-Width="40%" >
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Failure Count" ItemStyle-Width="10%" >
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server"></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
</Columns></GridView>
and my codebehind is:
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection();
connection.ConnectionString = ConfigurationManager.ConnectionStrings["SumooHAgentDBConnectionString"].ConnectionString;
connection.Open();
SqlCommand sqlCmd = new SqlCommand("SELECT FileName,FailureCount from Files where MachineID=#strID , connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlCmd.Parameters.AddWithValue("strID", strID);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
string nameoffiles = dt.Rows[i]["FileName"].ToString();
buFailureCode.Add(code);
string count = dt.Rows[i]["BuFailureCount"].ToString();
buFailureCount.Add(count);
}
}
connection.Close();
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
if (namesOfFiles.Count != 0)
{
for (int i = 0; i < namesOfFiles.Count; i++)
{
GridViewRow myRow = GridView1.Rows[i];
Label Label1 = (Label)myRow.FindControl("Label1");
Label Label3 = (Label)myRow.FindControl("Label3");
Label1.Text = namesOfFiles[i].ToString();
Label3.Text = buFailureCount[i].ToString();
}}}
set SortExpression
I think you'll have to handle the OnSorting event and do the actual sorting yourself in code-behind. The API documentation has an example.

Categories