To add new row in gridview using javascript - c#

In the below code i have gridview which has textbox and dropdownlist i want to add rows using javascript.My aim is to avoid postback on adding rows.
Markup code:
<asp:GridView runat="server" ID="gvProduct" AutoGenerateColumns="false"
Width="100%" CellPadding="4" ForeColor="#333333" ShowFooter="true"
PageSize-Mode="NumericPages" PagerStyle-Visible="true" AllowPaging="false" AllowSorting="true"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt"
OnRowDataBound="gvProduct_RowDataBound" OnRowCommand="gvProduct_RowCommand" OnRowDeleting="gvProduct_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="Product Name" ItemStyle-Width="350px">
<ItemTemplate>
<asp:DropDownList ID="ddlProduct" runat="server" AutoPostBack="false" Style="width: 100%; height:23px" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Current Stock" ItemStyle-Width="80px" Visible="false">
<ItemTemplate>
<asp:Label ID="lblCurrentStock" runat="server" onkeypress="return isNumberKey(event, false);" Height="20px" style="width:80px" Enabled="false" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity" ItemStyle-Width="80px">
<ItemTemplate>
<asp:TextBox ID="txtQuantity" onkeypress="return isNumberKey(event, false);" runat="server" Height="20px" Width="150px" onblur="js_function(this);" > </asp:TextBox>
<asp:Label ID="lblunittype" runat="server" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button2" OnClientClick="AddRow(); return false;" runat="server" Text="Button" />
Javascript code:
function AddRow() {
var table = document.getElementById('<%=gvProduct.ClientID %>');
var newRow = table.insertRow();
var i = 0;
for (i = 0; i < table.rows[0].cells.length; i++) {
var newCell = newRow.insertCell();
newCell.innerHTML = 'New Row';
}
}

Gridview in asp = Table in HTML
new row in Gridview in asp = new row in Table in HTML
Sample JavaScript code:
function AddRow() {
let tableRef = document.getElementById('MainContent_gvItems');
let newRow = tableRef.insertRow(-1);//inserts at last row
let Cell0 = newRow.insertCell(0);
let Text0 = document.createTextNode('mydata');
Cell0.appendChild(Text0);
}
Btw, GridView must be visible even it's empty.

If you just want to add rows to the table for presentation, then #Mostafa Shehata answer should work fine.
However adding rows in JavaScript does not attached it to the GridView datasource. Therefore you'll experience issues with processing the data in the backend (such as saving to database).
Two possible solutions:
Replace GridView with a html table. The data can be populated & updated using a JavaScript calls to a restful API.
Pre-populate the GridView datasource with empty rows.
Data-bind x amount of empty fields (for example 10 empty fields).
In the GridView markup hide all the rows using css.
Run JavaScript to show rows that are not empty.
The “add row” button can just show the first empty row.
Add some sort of notification, if all empty fields have been used. (for example: "please save your data, before continuing").
In code behind, remove all empty fields before consuming it.

Related

templateField Control are lost while deleting the other columns in gridview

I have a gridview :
<asp:GridView ID="grdData" OnRowCreated="GridData_RowCreated" runat="server" DataKeyNames="ID" AutoGenerateColumns="false" OnRowDataBound="grdData_RowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="editbtn" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
If I am trying to alter the gridview i.e when I am removing other columns except the existing template field the template field becomes empty:
int grdCount = grdData.Columns.Count;
for (int i = 1; i < grdData.Columns.Count; i++)
{
grdData.Columns.RemoveAt(1);
}
how to maintain the templateField Control while deleting the other columns in gridview.?
Please suggest.
Thanks in advance.
//You have to bind your grid view after deleting column.
public void bindGridData()
{
//Add your logic here which binds your grid.
grdData.Databind();
}
//You have to call above method after you delete a column from grid
view.
bindGridData();

data Grid Data bound field header text change in c#

I have a datagrid that has a BoundColumn there I am trying to change the header text on page load I so fa. I have tried this.
<asp:datagrid id="dgdata" runat="server" Width="658px" CellPadding="2" PageSize="2" DataKeyField="Name"
AutoGenerateColumns="False" ShowFooter="True" BorderColor="AliceBlue" OnItemDataBound="dgTranscript_ItemDataBound">
<Columns>
<asp:BoundColumn DataField="Name" HeaderText="" ItemStyle-VerticalAlign="Top"></asp:BoundColumn>
</Columns>
</asp:datagrid>
C#
dgdata.Columns[1].Visible = true;
dgdata.Columns[1].HeaderText = lblAverage.Text
I want to set the text to be the text that's inside that label but its not letting me if i say without the label it works
dgdata.Columns[1].Visible = true;
dgdata.Columns[1].HeaderText = "Some Text";
Binding Data
DataSet ds;
DataRow drClient = null;
dgdata.Columns[1].HeaderText = lblAverage.Text; // Here before the Daatabind I set the text to be that label
DataConn.WebExecute(out ds);
DataConn.Bind(dgTranscript, ds);// This binds the data to the datagrid
It shows that text as the header but when I try punting in any string or a label text it denies the whole header disappears
Thanks in advance. Best Regards
If the value of lblAverage is set after calling DataBind on the datagrid then the header will remain empty.
This works
lblAverage.Text = "Some Text";
dgdata.Columns[0].HeaderText = lblAverage.Text;
dgdata.DataSource = mySource;
dgdata.DataBind();
While this will not
lblAverage.Text = "Some Text";
dgdata.DataSource = mySource;
dgdata.DataBind();
dgdata.Columns[0].HeaderText = lblAverage.Text;
You can try this.
<asp:Label ID="lblAverage" runat="server" Text="Header Value"></asp:Label>
<asp:DataGrid ID="dgdata" runat="server" Width="658px" CellPadding="2" PageSize="2" DataKeyField="Name"
AutoGenerateColumns="False" ShowFooter="true" ShowHeader="true" BorderColor="AliceBlue">
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
<asp:Label ID="lblheader" runat="server" Text='<%# lblAverage.Text %>'></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblvalue" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

How to disable checkbox inside gridview?

Hi I am developing one application. I have one multiselect dropdownlist box. Whenever i select one value in dropdownlistbox corresponding value in gridview will be having checkbox in below gridview. I want to disable that checkbox. I am basically mvc developer and finding hard times to fix this. I am trying my level best to fix this. For example, whever i select some value in dropdown I am getting ID using jquery as below.
<script>
$(function() {
$('.limitedNumbSelect2').change(function (e) {
var selected = $(e.target).val();
});
});
This is my gridview.
<asp:GridView ID="gdvRegretletter" CssClass="tableform" runat="server" AutoGenerateColumns="False" DataKeyNames="Vendor_ID"
EmptyDataText="No records found !" ShowHeaderWhenEmpty="true" AllowPaging="true" OnPageIndexChanging="gdvRegretletter_PageIndexChanging">
<Columns>
<asp:TemplateField ShowHeader="true" HeaderText="Select All">
<HeaderTemplate>
<asp:CheckBox ID="checkAll" runat="server" Text="Check All" onclick="checkAll(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkselect" runat="server" onclick="Check_Click(this)" />
<asp:HiddenField ID="id" runat="server" Value='<%#Eval("Vendor_ID")%>' />
</ItemTemplate>
<HeaderStyle Width="8%" />
<ItemStyle VerticalAlign="Top" Width="8%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Username">
<ItemTemplate>
<asp:Label ID="lblUsername" runat="server" Text='<%#Eval("Username") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email Id">
<ItemTemplate>
<asp:Label ID="lblEmail" runat="server" Text='<%#Eval("Email") %>' />
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
Whenecer i select some value from multiselect dropdownlist box I get id in a variable selected. As soon as I get ID in a variable selected i want to disable that checkbox in gridview. May i have some suggestions on this! Thank you all
Furthur i tried as below.
This is jquery code to hide checkbox
$('.limitedNumbSelect2').change(function (e) {
selected = $(e.target).val();
`$(".disablechk[Text='selected']").prop("disabled", true);`
This is my checkbox code inside gridview.
<asp:CheckBox ID="chkselect" runat="server" onclick="Check_Click(this)" Text='<%#Eval("Vendor_ID")%>' class="disablechk"/>
I am trying to do whenever i get some value from dropdown slected i want to disable that particular checkbox.
If you are getting comma separated string then split it and make an array
var temp = new Array();
temp = selected.split(",");
then loop through it
$.each(temp, function( index, value ) {
$(".disablechk[Text='" + value + "']").prop("disabled", true);
});
You can loop the GridView HiddenField values and disable the checkbox accordingly.
<script type="text/javascript">
$(function() {
$('.limitedNumbSelect2').change(function (e) {
checkGridView($(e.target).val());
});
});
function checkGridView(selected) {
$('#<%= gdvRegretletter.ClientID %> input[type="hidden"]').each(function () {
if ($(this).val() == selected) {
var checkbox = $(this).prev();
checkbox.prop("disabled", true);
}
});
}
</script>

How to get the Id from Gridview of Chechbox.checked?

I have GridView and a button as follows. Then i am binding the gridview with data from my database. GridView has two hiddenfield for Id and ClassIndex.
when i selecting a checkbox and click button, i want to get the corresponding Id and FileName.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="check" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hdfId" runat ="server" Value='<%#Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hdfClssIndex" runat ="server" Value='<%#Eval("ClassIndex") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblFileName" runat ="server" Text='<%#Eval("FileName") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and Button Like
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Send Request" />
the code behind button is
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
var check = row.FindControl("check") as CheckBox;
if (check.Checked)
{
int Id = Convert.ToInt32(row.Cells[1].Text);
//some logic follws here
}
}
}
but i am getting an error like
Input string was not in a correct format.
What is the error and how to solve it?
Your looping correct.
But you forgot to notice one thing here, when you wanted to access CheckBox you did a FindControl on row. Which means you are trying to find some control in that row.
Then why are you accessing HiddenField control inside row with row.Cell[1].Text?
Try to find that also.
int Id = Convert.ToInt32(((HiddenField)row.FindControl("hdfId")).Value);

Display DataGrid Column as Hyperlink Column depending on column value

I have the below DataGrid which works with no problem
<asp:DataGrid ID="fileBrowserGrid" runat="server" Width="100%" PageSize="14" AllowPaging="True"
CellPadding="1" GridLines="None" BorderColor="#636E92" BorderWidth="0px" AutoGenerateColumns="False"
OnPageIndexChanged="fileBrowserGrid_PageIndexChanged">
<AlternatingItemStyle CssClass="mainbodytextalt"></AlternatingItemStyle>
<ItemStyle CssClass="metadatabodytext"></ItemStyle>
<HeaderStyle CssClass="metadatabodytitle"></HeaderStyle>
<FooterStyle CssClass="Blue"></FooterStyle>
<Columns>
<asp:BoundColumn DataField="LoadedFileID" HeaderText="Loaded File Id" Visible="False"></asp:BoundColumn>
<asp:BoundColumn DataField="DataSupplierCode" HeaderText="Data Supplier Code"></asp:BoundColumn>
<asp:BoundColumn DataField="DataSupplierName" HeaderText="Data Supplier Name"></asp:BoundColumn>
<asp:BoundColumn DataField="Filename" HeaderText="File Name"></asp:BoundColumn>
<asp:BoundColumn DataField="DateLoaded" HeaderText="Date Loaded"></asp:BoundColumn>
<asp:BoundColumn DataField="LoadStatus" HeaderText="Status"></asp:BoundColumn>
</Columns>
<PagerStyle CssClass="Gray"></PagerStyle>
</asp:DataGrid>
code behind:
DataSet dataSet = results.DataSet;
this.fileBrowserGrid.DataSource = dataSet;
this.fileBrowserGrid.DataBind();
I want to change the Status column so that will display a hyperlink to errormessage.aspx with id as querystring value if the value is 'Failed' but stay as normal text value if its anything else.
Ideally I don't want to make changes to my stored procedures
I've been looking at RowDataBind but haven't been able to get that working.
Any ideas? Thank you!
I have a solution with only the aspx and not touch the cs backend
You can predict the render of template Column. Try this
I suppose that the code status that indicate failed is "failed"
<asp:TemplateColumn>
<HeaderTemplate>
<b>Status </b>
</HeaderTemplate>
<ItemTemplate>
<asp:PlaceHolder ID="Ok" runat="server" Visible='<%# (Eval("LoadStatus").ToString()=="Failed"?false:true) %>'><%----%>
<asp:Label ID="Label1" Text='<%# Eval("LoadStatus") %>' runat="server" />
</asp:PlaceHolder>
<asp:PlaceHolder ID="Ko" runat="server" Visible='<%# (Eval("LoadStatus").ToString()=="Failed"?true:false) %>'><%----%>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# string.Format("DataLoaderErrorMessage.aspx?id={0}",Eval("LoadedFileID"))%>'><%# Eval("LoadStatus") %></asp:HyperLink>
</asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateColumn>
1) Set the AutoGenerateColumns property of the datagrid to false.
2) Create a template column instead of a bound column for the status.
3) Set the 'DataField' property for every column (Except the template column) so they know which value to display from the sql datasource.
4) Edit the template column and add a html div in there with the id divStatus
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<div id="divStatus" runat="server">
</div>
</ItemTemplate>
</asp:TemplateField>
Iterate through all the rows after setting the datasource of the gridview and do something like the following.
for(int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
{
HtmlGenericControl divStatus = (HtmlGenericControl)fileBrowserGrid.Rows[i].FindControl("divStatus");
if(dataSet.Tables[0].Rows[i]["LoadStatus"].ToString() != "Failed")
divStatus.InnerHtml = dataSet.Tables[0].Rows[i]["LoadStatus"].ToString();
else
divStatus.InnerHtml = "<a href='pageURL.aspx?ID=" + dataSet.Tables[0].Rows[i]["LoadedFileID"].ToString() + "'> Failed : " + dataSet.Tables[0].Rows[i]["LoadedFileID"].ToString() + "</a>";
}

Categories