I am binding the gridview and showing their corresponding total in footer without any error. Now I want to add extra runs as below highlighted in image(which is completely discrete datarow and it does not belong to dataset).I want to achieve functionality like below Image.
Here is my code :
<asp:GridView ID="gvFirstInningBatting" runat="server" AllowSorting="True" AutoGenerateColumns="false"
GridLines="None" AllowPaging="false" CellPadding="4" CssClass="GridViewStyle" OnRowDataBound="gvFirstInningBatting_RowDataBound"
ShowFooter="true" ShowHeader="true" Width="100%">
<Columns>
<asp:BoundField DataField="P_PlayerPopulerName" HeaderText="Batting" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Left" ItemStyle-Width="20%" />
<asp:BoundField DataField="SBTS_PlayerStatus" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Left" ItemStyle-Width="20%" />
<asp:BoundField DataField="SBTS_RunsScored" HeaderText="R" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
<asp:BoundField DataField="SBTS_MinutesBatted" HeaderText="M" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
<asp:BoundField DataField="SBTS_BallsPlayed" HeaderText="B" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
<asp:BoundField DataField="SBTS_Fours" HeaderText="4s" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
<asp:BoundField DataField="SBTS_Sixes" HeaderText="6s" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
<asp:BoundField DataField="SBTS_StrikeRate" HeaderText="SR" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
</Columns>
</asp:GridView>
In C#
protected void BindGridView(int scheduleId)
{
SqlConnection dBConnection = null;
try
{
dBConnection = new SqlConnection();
dBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["***"].ConnectionString;
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("SP_NAME", dBConnection);
cmd.CommandType = CommandType.StoredProcedure;
dBConnection.Open();
DataSet ds = new DataSet();
DataTable dtBatting = new DataTable();
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(ds);
int gvBattingCount = Convert.ToInt32(cmd.Parameters["#BattingRowsCount"].Value);
for (int i = 0; i < gvBattingCount; i++)
{
if (ds.Tables[i].Rows.Count > 0)
{
if (i == 0)
{
DataRow dr1st;
ds.Tables[i].DefaultView.RowFilter = "SBTS_PlayerIsBatted = 1";
dtBatting = ds.Tables[i].DefaultView.ToTable();
dr1st = dtBatting.NewRow();
dr1st["P_PlayerPopulerName"] = " ";
dr1st["SBTS_RunsScored"] = 36;
dr1st["SBTS_PlayerStatus"] = "Extras";
dr1st["SBTS_MinutesBatted"] = 0;
dr1st["SBTS_BallsPlayed"] = 0;
dr1st["SBTS_Fours"] = 0;
dr1st["SBTS_Sixes"] = 0;
dr1st["SBTS_StrikeRate"] = 0;
dtBatting.Rows.Add(dr1st);
gvFirstInningBatting.DataSource = dtBatting;
gvFirstInningBatting.DataBind();
}
}
}
}
the grid is working if I use dr1st["SBTS_Sixes"] = 0; but it shows 0 in the row and if I use dr1st["SBTS_Sixes"] = DBNull.Value; then it is throwing error
Object cannot be cast from DBNull to other types.
What should I do, Please help me out.
Related
I have problem when add information about total pages and total rows in footer gridview,
This my Html code;
<asp:GridView ID="GridView1" runat="server"
onpageindexchanging="GridView1_PageIndexChanging" AllowPaging="True"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
CellPadding="3" AutoGenerateColumns="False" Width="500px">
<Columns>
<asp:BoundField HeaderText="ProductId" DataField="ProductId" >
<ItemStyle Width="100px" />
</asp:BoundField>
<asp:BoundField HeaderText="ProductName" DataField="ProductName">
<ItemStyle Width="300px"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="SupplierId" DataField="SupplierId">
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
</Columns>
<PagerSettings FirstPageText="First" LastPageText="Last" PageButtonCount="7" Mode="NumericFirstLast" />
<RowStyle ForeColor="#000066" />
<FooterStyle BackColor="White" ForeColor="#000066" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
</asp:GridView>
This aspx code:
public void BindData()
{
string strConnection = #"Data Source=.\sa;Initial Catalog=Northwind;Integrated Security=SSPI;";
SqlConnection con = new SqlConnection(strConnection);
con.Open();
SqlCommand cmd = new SqlCommand("select ProductId, ProductName, SupplierId from Products", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
//Script row 10
int rowcount = ds.Tables[0].Rows.Count;
int remainingCount = 10 - (rowcount % 10);
for (int i = 0; i < remainingCount; i++)
{
DataRow row = ds.Tables[0].NewRow();
ds.Tables[0].Rows.Add(row);
}
//Script row ~10
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
My gridview
This my problem, I didnt find a way to add information total pages and rows
anybody can improve my code.
call this in your binding method
int TotalRecord = ds.Rows.Count(); //This is total number of records in gridview
GridView1.DataSource = ds;
GridView1.DataBind();
you can later call that Totalrecord in a label or something u want to be in your gridview refer here as well:https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.gridviewrowcollection.count?view=netframework-4.8
Every attempt to use the onrowupdating function a System.NullReferenceException error is thrown. The Gridview has no problem binding on page load and I can also delete rows without a problem.Here is my code:
Aspx..
<asp:GridView ID="datagrid" runat="server" DataKeyNames="Emp_ID" CssClass="EmployeeGridView" EditRowStyle-CssClass="GridViewEditRow" PagerStyle-CssClass="pager" HeaderStyle-CssClass="header" RowStyle-CssClass="rows"
AutoGenerateColumns="false" AllowPaging="true" OnRowCancelingEdit="OnRowCancelingEdit" OnRowDeleting="OnRowDeleting"
OnRowEditing="OnRowEditing" OnRowUpdating="OnRowUpdating"
OnPageIndexChanging="OnPageIndexChanging" PageSize="10"
>
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="Emp_ID" HeaderText="Employee ID" />
<asp:BoundField ItemStyle-Width="150px" DataField="FName" HeaderText="First Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="LName" HeaderText="Last Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="Email" HeaderText="Email" />
<asp:BoundField ItemStyle-Width="100px" DataField="DOB" HeaderText="DOB" />
<asp:BoundField ItemStyle-Width="150px" DataField="EmpRole" HeaderText="Role" />
<asp:BoundField ItemStyle-Width="150px" DataField="Notes" HeaderText="Notes" />
<asp:CommandField ShowEditButton="true" />
<asp:CommandField ShowDeleteButton="true" />
</Columns>
</asp:GridView>
c#..
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = datagrid.Rows[e.RowIndex];
int Emp_ID = Convert.ToInt32(datagrid.DataKeys[e.RowIndex].Values[0]);
string FName = (row.Cells[2].Controls[0] as TextBox).Text;
string LName = (row.Cells[3].Controls[0] as TextBox).Text;
string Email = (row.Cells[4].Controls[0] as TextBox).Text;
string DOB = (row.Cells[5].Controls[0] as TextBox).Text;
string role = (row.Cells[6].Controls[0] as TextBox).Text;
string notes = (row.Cells[7].Controls[0] as TextBox).Text;
string constr = ConfigurationManager.ConnectionStrings["MainFYPConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("UPDATE tbl_Employees SET FName=#FName, LName=#LName, Email=#Email, DOB=#DOB, EmpRole = Emp#Role, Notes = #Notes WHERE (Emp_ID = #Emp_ID)"))
{
cmd.Parameters.AddWithValue("#Emp_ID", Emp_ID);
cmd.Parameters.AddWithValue("#FName", FName);
cmd.Parameters.AddWithValue("#Lname", LName);
cmd.Parameters.AddWithValue("#Email", Email);
cmd.Parameters.AddWithValue("#DOB", DOB);
cmd.Parameters.AddWithValue("#EmpRole", role);
cmd.Parameters.AddWithValue("#Notes", notes);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
datagrid.EditIndex = -1;
this.BindGrid();
}
If anyone has any idea what is wrong the help would be greatly appreciated
I have a problem with my buttons in the grid view. It is not responding to my Response.Redirect("secondHistory.aspx") and my Console.WriteLine("hih"). Here is the HTML code
<asp:GridView runat="server" AutoGenerateColumns="false" ID="GridView1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowCommand="GridView_RowCommand" Width="1027px">
<Columns>
<asp:BoundField DataField="ExcelID" HeaderText="Excel ID" />
<asp:BoundField DataField="excelName" HeaderText="Excel Name" />
<asp:BoundField DataField="excelDescription" HeaderText="Excel Description" />
<asp:BoundField DataField="date / time" HeaderText="Date / Time" />
<asp:BoundField DataField="empID" HeaderText="Employee ID" />
<asp:BoundField DataField="empName" HeaderText="Employee Name" />
<asp:BoundField DataField="engID" HeaderText="Engineer ID" />
<asp:BoundField DataField="engName" HeaderText="Engineer Name" />
<asp:BoundField DataField="firstApproval" HeaderText="First Approval(Engineer)" />
<asp:TemplateField HeaderText="Second Approval (Manager)">
<ItemTemplate>
<asp:Button ID="acceptBtn" runat="server"
CommandName="Accept"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
Text="Accept" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and here is the backend code of the button.
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Accept")
{
// Retrieve the row index stored in the
// CommandArgument property.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button
// from the Rows collection.
GridViewRow row = GridView1.Rows[index];
// Add code here to add the item to the shopping cart.
Console.WriteLine("hih");
Response.Redirect("secondHistory.aspx");
}
}
Here is the code to populate the table if its necessary.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ExcelID", typeof(int));
dt.Columns.Add("excelName", typeof(string));
dt.Columns.Add("excelDescription", typeof(string));
dt.Columns.Add("date / time", typeof(string));
dt.Columns.Add("empID", typeof(int));
dt.Columns.Add("empName", typeof(string));
dt.Columns.Add("engID", typeof(int));
dt.Columns.Add("engName", typeof(string));
dt.Columns.Add("firstApproval", typeof(string));
dt.Columns.Add("secondApproval", typeof(string));
for(int i = 0; i < textfiles.Length; i++)
{
textList.Add(File.ReadAllText(textfiles[i]));
}
string[] textArray = textList.ToArray();
for (int i = 0; i < excelfiles.Length; i++)
{
dt.Rows.Add(i, excelfiles[i], textArray[i] , File.GetCreationTime(textfiles[i]), 837482, "*empName*", 917378, "*engName*", "Approved");
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
Please help thanks!
i am having an error : Object reference not set to an instance of an object. and the red text is:
dt.Rows[row.RowIndex]["Name"] = Name;
i want to edit data in my gridview. here is my code:
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
string Name = (row.Cells[0].Controls[0] as TextBox).Text;
string Price = (row.Cells[2].Controls[0] as TextBox).Text;
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[row.RowIndex]["Name"] = Name;
dt.Rows[row.RowIndex]["Price"] = Price;
ViewState["dt"] = dt;
gdview.EditIndex = -1;
this.GetProducts(0);
}
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
gdview.EditIndex = e.NewEditIndex;
this.GetProducts(0);
}
here is the getproducts()
private void GetProducts(int CategoryID)
{
ShoppingCart k = new ShoppingCart()
{
CategoryID = CategoryID
};
gdview.DataSource = null;
gdview.DataSource = k.GetAllProducts();
gdview.DataBind();
}
what am i missing here?
Another question. When i click on the update link, it shows the edit textbox on the Name, and Price fields. But the value on the name is not there? here is a screenshot.
here is my html code:
<Columns>
<asp:BoundField HeaderText="Name" DataField="Name" SortExpression="Name">
<ItemStyle Height="20px" Width="150px" />
</asp:BoundField>
<asp:BoundField HeaderText="ProductCategory " ReadOnly="true" DataField="CategoryName" SortExpression="CategoryNaame" >
<ItemStyle Height="20px" Width="150px" />
</asp:BoundField>
<asp:BoundField HeaderText="Price" DataField="Price" SortExpression="Price" >
<ItemStyle Height="20px" Width="150px" />
</asp:BoundField>
<asp:ImageField HeaderText ="ImageUrl" DataImageUrlField="ImageUrl" SortExpression="ImageUrl" ReadOnly="true" ControlStyle-Width ="10">
<ControlStyle Width="50px"></ControlStyle>
</asp:ImageField>
<asp:BoundField HeaderText="ProductQuantity" DataField="ProductQuantity" ReadOnly="true" SortExpression="ProductQuantity" >
<ItemStyle Height="20px" Width="150px" />
</asp:BoundField>
<asp:BoundField HeaderText="ProductSold" DataField="ProductSold" SortExpression="ProductSold" ReadOnly="true" >
<ItemStyle Height="20px" Width="150px" />
</asp:BoundField>
<asp:BoundField HeaderText="AvailableStock" DataField="AvailableStock" SortExpression="AvailableStock " ReadOnly="true" >
<ItemStyle Height="20px" Width="150px" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" Text="Edit" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton2" Text="Update" runat="server" OnClick="OnUpdate" />
<asp:LinkButton ID="LinkButton3" Text="Cancel" runat="server" OnClick="OnCancel" />
</EditItemTemplate>
</asp:TemplateField>
First you have to assign the datatable to ur viewstate. then you can able to update the value of the field.
FYI, I have bind the gridview by sqldatasource object.
Please check the code with this
if (!Page.IsPostBack)
{
try
{
gdview.DataSource = SqlDataSource1;
gdview.DataBind();
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
DataTable dt = new DataTable();
dt = dv.ToTable();
ViewState["dt"] = dt;
}
catch(Exception ex)
{
}
}
-----------------your other method
private void GetProducts(int CategoryID)
{
ShoppingCart k = new ShoppingCart()
{
CategoryID = CategoryID
};
gdview.DataSource = null;
gdview.DataSource = ViewState["dt"];
gdview.DataBind();
}
I have a DataGridView on a page. When I call that page whole list comes. I have decided to add pagination to the GridView.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" OnRowDeleting="GridView1_Del" OnSelectedIndexChanging="GridView1_Sel" OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="id" HeaderText="Id" SortExpression="id" Visible="false" />
<asp:BoundField DataField="name" HeaderText="Name" SortExpression="name" />
<asp:BoundField DataField="author" HeaderText="Author" SortExpression="author" />
<asp:BoundField DataField="active" HeaderText="Active" SortExpression="active" />
<asp:CommandField HeaderText="Delete" SelectText="Delete" ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
//Page_Load()
gridFill();
GridView1.AllowPaging = true;
GridView1.PageSize = 10;
gridFill() method fills the GridView.
public void gridFill()
{
conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/inetpub/example.com/db/db.mdb");
sql = "SELECT id, name, author, active, FROM [table]";
dt = new DataTable();
try
{
if (conn.State != ConnectionState.Open) conn.Open();
comm= new OleDbCommand(sql, conn);
da= new OleDbDataAdapter(comm);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
catch (System.Data.OleDb.OleDbException ex)
{
string msg = "Error: ";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
When I call the page it still gets all the rows at once. Also if I click 11th or later (because I limit the paging to 10 rows) rows for deleting I get index error.
So I have added another Button labeled as 'Refresh' which calls gridFill() method once more. Then pagination gets valid.
What could be the reason for GridView not paging for the first time?
If I change the order of the lines
//Page_Load()
gridFill();
GridView1.AllowPaging = true;
GridView1.PageSize = 10;
to
//Page_Load()
GridView1.AllowPaging = true;
GridView1.PageSize = 10;
gridFill();
it works. I can't believe it