<asp:Label ID="lblMRNNumber" runat="server" Text='<%# String.Concat(Eval("MRNNumber"))%>'> </asp:Label>
It display as
MRN-01
MRN-02
MRN-03
my requirement is
'MRN-01'
'MRN-02'
'MRN-03'
Text='<%# String.Concat("'",Eval("MRNNumber"),"'")%>' This gives error!
how to do this!
Try this
Text="<%#(Eval("MRNNumber","'{0}'"))%>"
This will be treated as
text=Eval("MRNNumber","'{0}'")
According to Gridview Item formatting:
Method 1:
Use BoundField, and intercept the GridView's RowDataBound event, in the
RowDataBound event, we can get the Binded Data from the certain GridView
Row's Cell
For Ex:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[2].Text = "'" + e.Row.Cells[2].Text + "'";
}
}
or:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl_Name = (Label)e.Row.FindControl("lblMRNNumber");
lbl_Name.Text = "'" + lbl_Name.Text + "'";
}
}
Method 2:
<asp:TemplateField HeaderText="TemplatePrice">
<ItemTemplate>
<asp:Label ID="lblMRNNumber" runat="server" Text='<%# AddDollar(Eval("MRNNumber").ToString()) %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
AddDolloar is the helper function defined in page class:
protected string AddDollar(string mystr)
{
return "'" + mystr + "'";
}
Take a look at this link
Related
Data in my GridView inside an UpdatePanel is going out of synch with the database and I can't figure out why. This has resulted in incorrect updates to the database which I have to fix rapidly! Can anyone help?
I have multiple UpdatePanels that have GridViews inside that can be edited by the user. There is a search feature and filter buttons that select queried data from the database and display in the GridView. There is sorting enabled and the "out of synchness" occurs mostly when sorting and then editing a field.
The data comes from a SQL Database. I can update the data directly through OnTextChange option of my TemplateField like this:
<asp:GridView
ID="GridView4"
runat="server"
OnSorting="TaskGridView_Sorting"
AllowSorting="True"
Width="100%" >
<Columns>
<asp:TemplateField SortExpression="name" HeaderText="Name">
<HeaderStyle HorizontalAlign="Left" CssClass="col_name" />
<ItemTemplate>
<asp:TextBox ID="name" AutoPostBack="True" CssClass="col_name" runat="server" Text='<%# Eval("name") %>' Width=180 OnTextChanged="text_change" />
</ItemTemplate>
</asp:TemplateField>
...
I have my gridview inside an UpdatePanel that has these options:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
...
I have enabled partial rendering like this:
<ajaxToolKit:ToolkitScriptManager EnablePartialRendering="true" runat="server" />
I have buttons that filter the data by requerying the database and displaying just the filtered data like this:
DataGrid_Load(DAL.Search_reg_log(OrgText.Text, searchText, searchCol), "reg");
The gridview gets its data loaded like this:
private void DataGrid_Load(DataTable command, string type)
{
DataTable dataTable = new DataTable();
dataTable = command;
string sortDir = ViewState["SortDirection"] as string;
string sortExp = ViewState["SortExpression"] as string;
if(ViewState["SortExpression"] != null)
{
dataTable = resort(dataTable, sortExp, sortDir);
}
try
{
var query = from c in dataTable.AsEnumerable()
where c.Field<string>("status") == "Invoiced" && c.Field<string>("reg_cat_id") != "Archive"
|| c.Field<string>("status") == "Confirmed" && c.Field<string>("reg_cat_id") != "Archive"
select c ;
if(query.Any()){
DataTable t2 = query.CopyToDataTable();
GridView4.DataSource = t2;
GridView4.DataBind();
} else {
GridView4.DataSource = new DataTable();
GridView4.DataBind();
}
}
catch(Exception e) {
ErrorText.Text = "Caught Exception: " + e;
}
...
I have isolated one cause of the data errors which occurs after sorting a column and then
protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExp = ViewState["SortExpression"] as string;
string sortDir = ViewState["SortDirection"] as string;
if(sortDir == "asc" & sortExp == e.SortExpression.ToString())
ViewState["SortDirection"] = "desc";
else
ViewState["SortDirection"] = "asc";
ViewState["SortExpression"] = e.SortExpression.ToString();
if(searchCol != "" && searchText != "")
DataGrid_Load(DAL.Search_reg_log(OrgText.Text, searchText, searchCol), "reg");
else
DataGrid_Load(DAL.reg_log(HeadText.Text, OrgText.Text), "reg");
UpdatePanels();
}
Here is the resort function:
public static DataTable resort(DataTable dt, string colName, string direction)
{
dt.DefaultView.Sort = colName + " " + direction;
dt = dt.DefaultView.ToTable();
return dt;
}
Please help with some direction of what might be causing this.
It looks like you are having some trouble with GridView and updating them. I will post a complete working example below. Start with that and gradually update that code to fit your own needs, like getting data with var query = from c in dataTable.AsEnumerable(). The important thing is to sort the data every time you (re)bind the GridView data. And I'm not sure what is happening inside resort, but you have to use dt.DefaultView.ToTable(); to save the sorting in the DataTable.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server"
DataKeyNames="ID" AllowSorting="true"
OnSorting="GridView1_Sorting"
AutoGenerateColumns="false"
AutoGenerateEditButton="true"
OnRowEditing="GridView1_RowEditing"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<ItemTemplate>
<%# Eval("ID") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="name">
<ItemTemplate>
<%# Eval("name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text=' <%# Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</ContentTemplate>
</asp:UpdatePanel>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
//bind data in an ispostback check
if (!IsPostBack)
{
DataGrid_Load();
}
}
private void DataGrid_Load()
{
//load the datatable data
DataTable dt = source;
//check if the viewsstate existst
if (ViewState["SortExpression"] != null && ViewState["SortDirection"] != null)
{
//sort the datatable before binding it to the gridview
dt.DefaultView.Sort = ViewState["SortExpression"] + " " + ViewState["SortDirection"];
dt.DefaultView.ToTable();
}
//bind the sorted datatable to the gridvidw
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//load the previous sorting settigns
string sortExp = ViewState["SortExpression"] as string;
string sortDir = ViewState["SortDirection"] as string;
//reverse the direction if the column is the same as the previous sort
if (sortDir == "asc" & sortExp == e.SortExpression.ToString())
ViewState["SortDirection"] = "desc";
else
ViewState["SortDirection"] = "asc";
//put the current sort column in the viewstate
ViewState["SortExpression"] = e.SortExpression.ToString();
//rebind data
DataGrid_Load();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
//set the edit index and rebind data
GridView1.EditIndex = e.NewEditIndex;
DataGrid_Load();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//reset the edit index and rebind data
GridView1.EditIndex = -1;
DataGrid_Load();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//use findcontrol to locate the textbox in the edit template
TextBox tb = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");
//get the id of the row from the datakeys
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
//show result for testing
Literal1.Text = "ID: " + id + "<br>Name: " + tb.Text;
//reset the edit index and rebind data
GridView1_RowCancelingEdit(null, null);
}
I use a Checkbox in a Repeater, how can I know which
Checkbox have changed in OnCheckedChanged?
I have tried to set id then checkbox is binding data, but
it will not work. Hope someone can help me
Thanks
/Mats
Check the sender(Event Target) parameter
protected void Chb_Changed(object sender, EventArgs e)
{
if (sender != null)
{
CheckBox cb=(CheckBox)sender;
string clickedCheckBoxID=cb.ID;
}
}
Try following . Please note that we can also bind some primary column let's say "ID" column in some hidden field then get in code behind.
ASPX Side
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="sqldtasource" >
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" AutoPostBack="true" Text='<%#Bind("Name")%>' OnCheckedChanged="Chb_Changed"/>
<asp:HiddenField ID="hdn_ID" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "ID") %>'/>
</ItemTemplate>
</asp:Repeater>
Code Behind :
protected void Chb_Changed(object sender, EventArgs e)
{
if (sender != null)
{
try
{
var hdnID = (HiddenField)checkBox.NamingContainer .FindControl("hf_ID");
if(hdnID != null)
{
string primaryFieldValue = hdnID.Value;
}
if (((CheckBox)sender).Checked)
{
Response.Write(((CheckBox)sender).Text + " is checked");
}
}
catch {
}
}
}
This is my grid view
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
OnRowDeleting="GridView1_RowDeleting"
OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating"
OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="name" HeaderText="name" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btn1" Text="edit" runat="server" CommandArgument='<%#Eval("id") %>' CommandName="Edit" ></asp:LinkButton>
<asp:LinkButton ID="Button1" Text="delete" runat="server" CommandArgument='<%#Eval("id") %>' CommandName="Delete" OnClientClick=' return confirm("do you want to delete")' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is the function call
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Response.Write(e.CommandArgument.ToString());
if (e.CommandName == "Delete")
{
//Response.Write(e.CommandArgument);
MySqlConnection conn = new MySqlConnection(connectionString);
conn.Open();
string query = "delete from brand where id='" + e.CommandArgument + "'";
MySqlCommand cmd = new MySqlCommand(query,conn);
cmd.ExecuteNonQuery();
conn.Close();
fillgrid();
}
}
The onrowcommand does not get fired. Why?
Just guessing: because your Page_Load looks similar to this:
protected void Page_Load(Object sender, EventArgs e)
{
DataBindGridView(); // here you load the datasource of the grid and call DataBind();
}
Do not DataBind the grid on postbacks, otherwise events aren't triggered since you overwrite changes with the values form database, so this should work then:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
DataBindGridView(); // here you load the datasource of the grid and call DataBind();
}
Enable viewstate:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="something.cs"
ValidateRequest="false" Inherits="something" EnableViewState="true" %>
In the Page load event, do:
if(!IsPostback)
{
callmethodtobindgrid();
}
Rowcommand event handler:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Response.Write(e.CommandArgument.ToString());
if (e.CommandName == "Delete")
{
//Response.Write(e.CommandArgument);
MySqlConnection conn = new MySqlConnection(connectionString);
conn.Open();
string query = "delete from brand where id='" + e.CommandArgument + "'";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.ExecuteNonQuery();
conn.Close();
fillgrid();
}
}
I would like to get name of column which I click and value of this clicked row.
I found very good example but I`m not able to get this data which I want.
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onClick"] = "location.href='view.aspx?id_lekarza=" + DataBinder.Eval(e.Row.DataItem, "Id_lekarza") + " &klikniete=" + "sss" + " '";
}
}
e.Row.RowIndex all the time 0?
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", "javascript:alert('" + e.Row.RowIndex + "');");
e.Row.Style.Add("cursor", "pointer");
}
}
In your GridView you can add a template field like below :
<asp:TemplateField ItemStyle-Width="44px" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle"
HeaderStyle-Height="40px" ShowHeader="false">
<ItemTemplate>
<asp:ImageButton ID="btnSelect" runat="server" ImageUrl="~/Images/btnSelect.png"
CommandName="Select" CommandArgument='<%# Eval("ID") %>'/></ItemTemplate>
<HeaderStyle Height="40px"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="44px"></ItemStyle>
</asp:TemplateField>
And in your C# codebehind You should create the RowCommand event of the Gridview , and access the CommandArgument of that row like following:
protected void GV_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
//You get the ID of that specific row that you have selected :
string ID=e.CommandArgument.ToString();
//Here you write your code ! For example a select query to get that row from database by the ID you have gained in above line of code
}
}
I have a gridview in which every row contains a dropdownlist. I want to bind every dropdownlist dynamically. Can someone tell me how can i do it. Thanks in Advance
If you are using template column then you can bind your drop-down from mark-up using data-binding expressions. For example,
<asp:TemplateField HeaderText="XYZ">
<ItemTemplate>
<asp:DropDownList runat="server" ID="MyDD" DataSourceId="MyDataSource" />
</ItemTemplate>
</asp:TemplateField>
Above is assuming that your drop-down data in constant across rows. If it is changing then you can use data-binding expression such as
<asp:DropDownList runat="server" DataSource='<%# GetDropDownData(Container) %>' DataTextField="Text" DataValueField="Value" />
GetDropDownData will be a protected method in code-behind that will return the data (data-table, list, array) for the given row.
You can use GridView.RowDataBound event (or RowCreated event) in code-behind to fill drop-downs. For example,
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Find the drop-down (say in 3rd column)
var dd = e.Row.Cells[2].Controls[0] as DropDownList;
if (null != dd) {
// bind it
}
/*
// In case of template fields, use FindControl
dd = e.Row.Cells[2].FindControl("MyDD") as DropDownList;
*/
}
}
In addition to the proposed methods, you may also bind your controls within your markup, in this way:
<asp:GridView ID="MyGrid" runat="server" DataSourceID="MyDataSource1">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind ("CustomerId") %>' DataSourceID="CustomersDataSource" DataTextField="CustomerName" DataValueField="CustomerId" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is your gridview
<asp:GridView ID="grvExcelData" runat="server" onrowdatabound="GridView2_RowDataBound">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="DrdDatabase" Width="100px" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and your RowDataBound event for the gridview would be
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
string cities = "maxico,chennai,newdelhi,hongkong";
string [] arr = cities.Split(',');
// Instead of string array it could be your data retrieved from database.
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("DrdDatabase");
foreach (string colName in arr )
ddl.Items.Add(new ListItem(colName));
}
}
protected void gvSalesAppData_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlCurrentPhase = (DropDownList)e.Row.FindControl("ddlCurrentPhase");
DropDownList ddlProductFamily = (DropDownList)e.Row.FindControl("ddlProductFamily");
DropDownList ddlProductGroup = (DropDownList)e.Row.FindControl("ddlProductGroup");
DropDownList ddlETProgramManager = (DropDownList)e.Row.FindControl("ddlETProgramManager");
DropDownList ddlPLMForTheProduct = (DropDownList)e.Row.FindControl("ddlPLMForTheProduct");
TrackingToolObj.BindCurrentPhases(ddlCurrentPhase);
TrackingToolObj.BindCurrentPhases(ddlProductFamily);
TrackingToolObj.BindProductGroups(ddlProductGroup);
TrackingToolObj.GetEmployeesBasedOnRoleTypeId(ddlETProgramManager, (int)OSAEnums.RoleTypes.ProgramManager, false);
TrackingToolObj.GetEmployeesBasedOnRoleTypeId(ddlPLMForTheProduct, (int)OSAEnums.RoleTypes.PLM, false);
}
}
Binding the GridView
Below is the code to Bind the GridView control with data.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string query = "SELECT top 10 * FROM Customers";
SqlCommand cmd = new SqlCommand(query);
gvCustomers.DataSource = GetData(cmd);
gvCustomers.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}