how to set data from sql query into the gridview template field - c#

In my SQL query I retrieve 3 strings and the 3rd string has an URL. I created 2 templatefield contain labels and another template with an image. Now I want to set the values to the two labels and view the image by setting ImageUrl and display all the rows coming out from SQL query.
protected void Page_Load(object sender, EventArgs e)
{
//if (IsPostBack == false)
//{
// grdMaterial.DataBind();
//}
try
{
matType = int.Parse(Session["mattype"].ToString());
colorId = int.Parse(Session["color"].ToString());
matStyleId = int.Parse(Session["matstyle"].ToString());
try
{
matContent = Session["matContent"].ToString();
}
catch
{
panAval.Visible = true;
panNew.Visible = false;
dtab = new DBHELPER().getdataTable("SELECT [item_Id],[mat_Content],[mat_Image] FROM [item] WHERE [mat_Content]='" + matContent + "'");
//grdMaterial.DataSource = dtab;
//grdMaterial.DataBind();
}
catch (Exception ee)
{
}
}
protected void grdMaterial_Load(object sender, EventArgs e)
{
try
{
for (int i = 0; i < dtab.Rows.Count; i++)
{
//TextBox x = (TextBox)GridViewCarrinho.Rows[row.RowIndex].Cells[2].FindControl("txtQuantidade");
Label itemId = (Label)grdMaterial.FindControl("lblItemId");
itemId.Text = dtab.Rows[i]["item_Id"].ToString();
Label matContent = (Label)grdMaterial.FindControl("lblItemName");
matContent.Text = dtab.Rows[i]["mat_Content"].ToString();
Image itemImage = (Image)grdMaterial.FindControl("imgItemImage");
itemImage.ImageUrl = dtab.Rows[i]["mat_Image"].ToString();
}
}
catch (Exception ee)
{
}
}

This event: grdMaterial_Load does not seem necessary.
You can simply bind your datasource to your datagrid and simply customize the datagrid to get the image, and populate the labels.
Simply bind your ItemID and ItemName columns, then create a template field for the image as shown below...
<asp:GridView ID="grdMaterial" runat="server" DataKeyNames="item_Id" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="item_Id" HeaderText="Item Id" />
<asp:BoundField DataField="mat_Content" HeaderText="Item Name" />
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:Image ID="imgItemImage" runat="server" ImageUrl="<%# DataBinder.Eval(Container.DataItem, "mat_Image")) %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Related

How do i get id of colunm in gridview c# asp.net and open another page using that id?

How do i get id of column in grid view c# asp.net using a button and the open another web-part that will collect information fromsl server using that id from grid-view?
I have done this for my grid view:
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnView" runat="server" Text="View" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And for the information from sqlserver that is being filled in gridview the code is:
protected void GridView_Load(object sender, EventArgs e)
{
using (DBEntitiesModelConn DbContext = new DBEntitiesModelConn())
{
try
{
GridView.AutoGenerateColumns = true;
var ApplicationData = from i in DbContext.DBEntity
select new
{
CompanyName = i.Name.ToString(),
ApplicationStatus = i.Status.ToString(),
ApplicationDate = i.DateSubmitted.ToString(),
ApplicationID = i.ID.ToString(),
};
GridView.DataSource = ApplicationData.ToList();
GridView.DataBind();
}
catch (System.Data.SqlClient.SqlException ex)
{
ErrorMessage.Text = ex.Message.ToString();
}
}
}
protected void OnRowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(ViewApplicationsGrid, "Select$" + e.Row.RowIndex);
e.Row.ToolTip = "Click to select this row.";
}
}

Getting gridview checked boxes

I have this template field
<asp:TemplateField ItemStyle-Width="40px">
<HeaderTemplate>
<asp:CheckBox ID="chkboxSelectAll" runat="server" AutoPostBack="true" OnCheckedChanged="chkboxSelectAll_CheckedChanged" />
</HeaderTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemTemplate>
<asp:CheckBox ID="chkEmp" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
In the code-behind I have this code:
protected void chkboxSelectAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox ChkBoxHeader = (CheckBox)grdGeral.HeaderRow.FindControl("chkboxSelectAll");
foreach (GridViewRow row in grdGeral.Rows)
{
CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkEmp");
if (ChkBoxHeader.Checked == true)
{
ChkBoxRows.Checked = true;
}
else
{
ChkBoxRows.Checked = false;
}
}
}
protected void btnLista_Click(object sender, EventArgs e)
{
string strEmailTotal = "";
string strEmail = "";
foreach (GridViewRow row in grdGeral.Rows)
{
CheckBox chkBx = (CheckBox)grdGeral.FindControl("chkEmp");
if (chkBx != null)
{
if (chkBx.Checked)
{
strEmail = ((Label)grdGeral.FindControl("lblEmail")).Text;
strEmailTotal = strEmailTotal + "," + strEmail;
}
}
}
lblMail.Text = strEmailTotal ;
}
I always get a null value for the checkbox, even if I set the default value to "true" in the templatefield. Can anyone help me with this?
Thank you
In your btnLista_Click event you should use row instead grdGeral:
CheckBox chkBx = (CheckBox)row.FindControl("chkEmp");
And below this the same:
strEmail = ((Label)row.FindControl("lblEmail")).Text;
try this solution.
foreach (GridViewRow row in grdGeral.Rows)
{
CheckBox chkBx = row.FindControl("chkEmp") as CheckBox ;
}

Adding Dynamic Rows in Gridview and How to retain selected option from user control in Gridview

I have created user control named CRE.ascx,this control has 3 dropdownlist.
First dropdownlist bind data on pageload.Second and third based on SelectedIndexChanged.
<table cellspacing="0" cellspading="0" style="width:550px;height:30px;">
<tr>
<td style="width:30%;">
<asp:DropDownList ID="ddlCRE" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlCRE_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:30%;">
<asp:DropDownList ID="ddlDataPoints" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlDataPoints_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:30%;">
<asp:DropDownList ID="ddlErrorCode" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlErrorCode_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:10%;">
<asp:TextBox ID="tbxErrorScore" runat="server" style="height:17px;border:0px;font-family:'Segoe UI';font-size:13px;font-weight:500;color:white;background-color:#333333;
width:65px;" ReadOnly="true"> </asp:TextBox>
</td>
</tr>
</table>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Get Ticket Type Values
dbtickettype = helpdsktcktusrHandler.GetTicketType("DPT0001");
ddlCRE.DataSource = dbtickettype;
ddlCRE.DataValueField = "Type_ID";
ddlCRE.DataTextField = "Type_Name";
ddlCRE.DataBind();
ddlCRE.Items.Insert(0, new ListItem("Select Type", "SLCT0000"));
}
else
{
}
}
protected void ddlCRE_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedTypeID = ddlCRE.SelectedValue.ToString();
try
{
if (selectedTypeID == "SLCT0000")
{
ddlDataPoints.Items.Clear();
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketCategory = helpdsktcktusrHandler.GetTicketCategoryDetails(selectedTypeID);
//Binding Ticket Type values to Listbox
ddlDataPoints.DataSource = dbticketCategory;
ddlDataPoints.DataValueField = "Category_ID";
ddlDataPoints.DataTextField = "Category_Name";
ddlDataPoints.DataBind();
ddlDataPoints.Items.Insert(0, new ListItem("Select Category", "SLCT0000"));
//Clear Items
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
protected void ddlDataPoints_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCatID = ddlDataPoints.SelectedValue.ToString();
try
{
if (selectedCatID == "SLCT0000")
{
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketSubCategory = helpdsktcktusrHandler.GetTicketSubCategoryDetails(selectedCatID);
//Binding Ticket Type values to Listbox
ddlErrorCode.DataSource = dbticketSubCategory;
ddlErrorCode.DataValueField = "Sub_Category_ID";
ddlErrorCode.DataTextField = "Sub_Category_Name";
ddlErrorCode.DataBind();
ddlErrorCode.Items.Insert(0, new ListItem("Select Subcategory", "SLCT0000"));
//Clear Items
tbxErrorScore.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
protected void ddlErrorCode_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedSubcatID = ddlErrorCode.SelectedValue.ToString();
try
{
if (selectedSubcatID == "SLCT0000")
{
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketIssues = helpdsktcktusrHandler.GetTicketIssueDetails(selectedSubcatID);
////Binding Ticket Type values to Listbox
//ddlstIssue.DataSource = dbticketIssues;
//ddlstIssue.DataValueField = "IssueID";
//ddlstIssue.DataTextField = "Issue_Name";
//ddlstIssue.DataBind();
tbxErrorScore.Text = dbticketIssues.Rows[0][1].ToString();
}
}
catch (Exception ex)
{
}
}
then register directive and an instance of the user control added to the page.
In this main page, i have added one Gridview, user control UC1 and two buttons
included in the ItemTemplate.
<%# Register src="~/CRE.ascx" TagName="InsertNewCRE" TagPrefix="uc1" %>
<asp:UpdatePanel ID="MainUpdatePanel" runat="server">
<ContentTemplate>
<div id="dvsubCRE" class="dvsubCRE" runat="server">
<!-----[[[ GRIDVIEW ADDING CRE ]]]----->
<div id="dvAddingErrorInfo" class="dvAddingErrorInfo">
<!-- LOAD CRE DROPDOWN INFO GRID -->
<asp:GridView ID="gvCREInfo" runat="server" CssClass="gvErrorInfo" AlternatingRowStyle-CssClass="" ShowFooter="false" ShowHeader="false"
EnableViewState="True" GridLines="None" EmptyDataText="No records found" AutoGenerateColumns="true" CaptionAlign="Left" CellPadding="0"
ShowHeaderWhenEmpty="True" OnRowCreated="gvCREInfo_RowCreated" OnRowCommand="gvCREInfo_RowCommand" >
<Columns>
<asp:BoundField DataField="RowNumber" />
<asp:TemplateField ItemStyle-Width="25%" ItemStyle-Height="20px">
<ItemTemplate>
<uc1:InsertNewCRE id="UC1InserCRE" runat="server" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgbtnAddCRE" runat="server" Width="20px" Height="20px" value="" ImageUrl="~/Images/Tracker/add.png"
CommandName="ButtonAddCRERow" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<asp:ImageButton ID="imgbtnReoveCRE" runat="server" Width="20px" Height="20px" value="" Visible="false" ImageUrl="~/Images/Tracker/delete.png" CommandName="ButtonRemoveCRERow" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!-- LOAD CRE DROPDOWN INFO GRID CLOSE -->
</div>
<!-----[[[ GRIDVIEW ADDING CRE CLOSE ]]]----->
</div>
</ContentTemplate>
</asp:UpdatePanel>
When main page loads, user control UC1 loaded in the gridview and pull out the data from CRE.ascx page.I have bind dummy data on page load to the gridview.Add new row along with user control mentioned in the RowCommand.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
gvCREInfo.DataSource = dt;
gvCREInfo.DataBind();
}
else
{
}
}
catch (Exception ex)
{
}
}
protected void gvCREInfo_RowCommand(object sender, GridViewCommandEventArgs e)
{
#region ADD NEW CRE ROW
if (e.CommandName == "ButtonAddCRERow")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvCREInfo.Rows[index];
int count = gvCREInfo.Rows.Count;
DataRow drCurrentRow = null;
UserControl UC1 = (UserControl)(row.Cells[0].FindControl("UC1InserCRE"));
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
for (int i = 0; i <= (count - 1); i++)
{
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows.Add(drCurrentRow);
}
gvCREInfo.DataSource = dtCurrentTable;
gvCREInfo.DataBind();
}
#endregion
}
When i run this code working fine and i changed the first dropdownlist
it will pull data and bind to the second, like wise third one also.But when i click the add button selected data lost in the first row and second row control added not with data.How to retain existing selected data and load user control along with data it should not loss data event post back.Please help me and sort out this.
![enter image description here][1]
http://i.stack.imgur.com/wdYZv.jpg

Why do checkboxes in the gridview firstly after checking and afterwards unchecking in the PreRender stage eventually are checked?

Please help me with following, just something weird is going on.
I have a gridview with paging where the first column is filled with checkboxes.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="..." DataKeyNames="EventID" EnableViewState="false"
GridLines="None" AllowSorting="True"
AllowPaging="True" Width="100%"
onpageindexchanging="GridView1_PageIndexChanging"
onprerender="GridView1_PreRender">
<HeaderStyle Wrap="false" />
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left">
<HeaderTemplate>
<asp:CheckBox ID="SelectAllEvs" runat="server" EnableViewState="false" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="EventSelector" runat="server" EnableViewState="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ... >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField ... >
</asp:BoundField>
<asp:BoundField ... >
</asp:BoundField>
</Columns>
</asp:GridView>
CodeBehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["PageIndex"] != null)
{
GridView1.PageIndex = Convert.ToInt32(Session["PageIndex"]);
}
}
}
protected void GridView1_PreRender(object sender, EventArgs e)
{
// loading checkbox values from the session collection
GridView gv = (GridView)sender;
LoadCheckboxState(gv);
Session["PageIndex"] = gv.PageIndex;
}
private void LoadCheckboxState(GridView gv)
{
for (int i = 0; i < gv.Rows.Count; i++)
{
var chkBox = GridView1.Rows[i].FindControl("EventSelector") as CheckBox;
int id = gv.PageIndex * gv.PageSize + i;
if (SelectedIndexes.Contains(id))
{
chkBox.Checked = true;
}
else
{
chkBox.Checked = false;
}
}
}
private List<int> SelectedIndexes
{
get
{
if(Session["selectedRows"] == null)
{
Session["selectedRows"] = new List<int>();
}
return (List<int>)Session["selectedRows"];
}
}
private void SaveCheckboxState(GridView gv)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
var chkBox = GridView1.Rows[i].FindControl("EventSelector") as CheckBox;
int id = gv.PageIndex * gv.PageSize + i;
if (chkBox.Checked)
{
//see if we have an id added already
if (!SelectedIndexes.Contains(id))
{
SelectedIndexes.Add(id);
}
}
else
{
if (SelectedIndexes.Contains(id))
{
SelectedIndexes.Remove(id);
}
}
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
// saving current page checkbox values to the session collection
GridView gv = (GridView)sender;
SaveCheckboxState(gv);
GridView1.PageIndex = e.NewPageIndex;
}
When I first get to my page I check some checkboxes and then press F5. Apparently after pressing it I dont have any values in SelectediIndexes and all unselected checkboxes must be checked = false on the PreRender stage but they appear checked after all this. And the problem of the same nature: I checked some on the first page; went to the second page (currently having 2 indexes in the SelectedValues) and after pressing F5 the same I have checked the same checkboxes as on the first page, though they mustn't. I'm absolutely confused with this. How can I fix this? Thanx for any help.
I've found the reason to that strange behavior. I'm using Firrefox. And one of the features of this browser is saving state of some fields when refreshing the page. If you want to refresh a page fully you should refresh it with pressed shift button. Tested in Google Chrome - works just fine.

.NET checkbox.Checked always return false

i'm a newby at .NET and I'm having a problem with my checkboxes. They all return false, even if they are selected. Here is my asp code
<asp:GridView ID="gvGeneros1" runat="server" class="divTable"
AutoGenerateColumns="False" DataKeyNames="idgenero" CssClass="table">
<Columns>
<asp:BoundField DataField="nome" HeaderText="GĂȘnero" SortExpression="nome" >
<ControlStyle Width="200px" />
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:TemplateField AccessibleHeaderText="Check">
<ItemTemplate>
<asp:CheckBox ID="checkGenero" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and here's my c# code
DataSet dsDivided;
protected void Page_Load(object sender, EventArgs e)
{
Music musicbll = new Music();
DataSet dsGeneros = musicbll.getGenders();
int size = dsGeneros.Tables[0].Rows.Count;
dsDivided = null;
// Divide in two DataTable
dsDivided = Tools.SplitDataTableInTwo((DataTable)dsGeneros.Tables[0], size / 2);
gvGeneros1.DataSource = dsDivided.Tables["FirstSet"];
gvGeneros1.DataBind();
for (int i = 0; i < gvGeneros1.Rows.Count; i++)
{
((CheckBox)gvGeneros1.Rows[i].Cells[1].Controls[1]).Checked=false;
}
}
protected void btGravarPrefs_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable("generos");
dt.Columns.Add("idgenero", typeof(int));
dt.Columns.Add("active", typeof(bool));
for (int i = 0; i < gvGeneros1.Rows.Count; i++)
{
int idCliente = (int)dsDivided.Tables[0].Rows[i][0];
bool check = ((CheckBox)gvGeneros1.Rows[i].Cells[1].Controls[1]).Checked; //always false
dt.Rows.Add(new object[] { idCliente, check});
}
}
}
I don't know what to try more, and i search all over and it seems right. Thanks
I think you should wrap your Data binding with if (!Page.IsPostBack)
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Bind your datasource here
}
}

Categories

Resources