Add To The Top in the DataList - asp.net

This My code For binding My DataList ,and every item in datalist have a different button ,
the items sorted correctly by date but the index for each item not sorted with it ,
ex:
when insert a new data in employees table the data shows correct(sorted by date),the last employee was insert into employee table shows in the first item and take the index 0.
I want to know how i can to make his index The Last Index in my old data + 1 ?
private void bind()
{
da2 = new SqlDataAdapter("select * from employees order by insert_date desc", m_SqlConnection);
DataSet dataSet2 = new DataSet();
da2.Fill(dataSet2, "det");
DataList1.DataSource = dataSet2.Tables["det"];
DataList1.DataBind();
}
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
Button btn = (Button)e.Item.FindControl("button4");
Button btn2 = (Button)e.Item.FindControl("button1");
da2 = new SqlDataAdapter("select insert_stat from insert_detail where user_id='" + int.Parse(Session["id"].ToString()) + "'", m_SqlConnection);
DataSet dataSet2 = new DataSet();
da2.Fill(dataSet2, "chk");
if (dataSet2.Tables["chk"].Rows[e.Item.ItemIndex]["insert_stat"].ToString() == "accept")
{
btn.Visible = true;
btn2.Visible = true;
}
else
{
if (dataSet2.Tables["chk"].Rows[e.Item.ItemIndex]["insert_stat"].ToString() == "reject")
{
btn.Visible = false;
btn2.Visible = false;
}
}
}

This is more a SQL problem than a DataList issue.
I recommend that you rewrite your SQL in the bind() method to do a JOIN on the insert_detail table to get the accept or reject value out of the table and into the bound data set for the data list. This serves two benefits:
It eliminates the database call in the DataList1_ItemDataBound() method, which if you have dozens or hundreds of rows, then that is dozens or hundreds less database calls.
It allows you to put the insert_stat value into a HiddenField control in your DataList and then check the value in the DataList1_ItemDataBound event, like this:
HiddenField theHiddenField = e.Item.FindControl("HiddenField1") as HiddenField;
// Make sure we found the control, because the as operator
// returns null for a failed cast
if(theHiddenField != null)
{
if(theHiddenField.Value.ToLower() == "accept")
{
btn.Visible = true;
btn2.Visible = true;
}
else
{
btn.Visible = false;
btn2.Visible = false;
}
}

Related

Sort the grid view after merging cells using OnDataBound asp:net gridview

private void GridViewBind()
{
SqlConnection Dbcon = new SqlConnection();
Dbcon.ConnectionString = ConfigurationManager.ConnectionStrings[
"ConnectionString"].ConnectionString;
Dbcon.Open();
string expSql = "SELECT [dName],[item],[cnt] FROM [Test1].[dbo].[Test3]
ORDER BY [dName], [cnt] desc";
SqlDataAdapter adAdapter = new SqlDataAdapter(expSql, Dbcon);
DataSet ds = new DataSet();
adAdapter.Fill(ds);
GridView.DataSource = ds.Tables[0];
GridView.DataBind();
ViewState["dt"] = ds.Tables[0];
ViewState["sort"] = "Desc";
}
I drew a table using gridview(asp:gridview) And I made a db for test and bound it
Then, in order to merge cells with the same subject, cells were merged using OnDataBound.
I want to sort by merged subject when cnt is clicked
However, my sort code sorts the entire cnt column, and the merged cells are unraveled.
I need a way to keep the merged cells and do ASC/DESC sorting within them!
protected void OnDataBound(object sender, EventArgs e)
{
for (int i = GridView2.Rows.Count - 1; i > 0; i--)
{
GridViewRow row = GridView2.Rows[i];
GridViewRow previousRow = GridView2.Rows[i - 1];
int j = 0;
if (row.Cells[j].Text == previousRow.Cells[j].Text)
{
if (previousRow.Cells[j].RowSpan == 0)
{
if (row.Cells[j].RowSpan == 0)
{
previousRow.Cells[j].RowSpan += 2;
}
else
{
previousRow.Cells[j].RowSpan = row.Cells[j].RowSpan + 1;
}
row.Cells[j].Visible = false;
}
}
}
}
I don't have reputation to comment, so i comment here in answer.
Can you add your OnDataBound code where your merged subject?
Also can you make your select query with merged subject as column, then you just need to bind data directly to gridview.
For sorting you can follow below link:
https://www.c-sharpcorner.com/UploadFile/b8e86c/paging-and-sorting-in-Asp-Net-gridview/
https://codepedia.info/gridview-sorting-header-click

how to get gridview all rows data when using paging

I have a gridview with paging (page size 10), which contains Course details. when i am saving gridview data into database it save only 10 record (according to page).
is there any to get all gridview all rows.
e.g. if my gridview contains 25 rows with paging and when i save data into database then all 25 rows data insert into database?
please help...
Here is my code
DataTable dt = new DataTable();
dt.Columns.Add("row_index");
dt.Columns.Add("edited_value");
IList<int?> SeqNos = new List<int?>();
foreach (GridViewRow gvr in gvViolationCodes.Rows)
{
TextBox tb = (TextBox)gvr.FindControl("txtSeqNo");
Label lblSysid = (Label)gvr.FindControl("lblSysID");
HiddenField hf = (HiddenField)gvr.FindControl("HiddenField1");
if (tb.Text != hf.Value)
{
DataRow dr = dt.NewRow();
SeqNos.Add(Convert.ToInt32(tb.Text));
dr["row_index"] = lblSysid.Text;
dr["edited_value"] = tb.Text;
dt.Rows.Add(dr);
}
}
You need to save the data in temporary storage in PageIndexChanging event of GrIdView. On final save send the datatable to Sql Server Procedure or loop through the datatable and save it in database. Follow the steps:
protected void grdView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
fnStoreGridData();
}
private void fnStoreGridData()
{
DataTable TempDataTable = new DataTable();
if(Session["Data"]!=null){
TempDataTable = Session["Data"] as DataTable;
}
else{
TempDataTable.Columns.Add("exCourse", typeof(string)) ;
TempDataTable.Columns.Add("exUniversityCourse", typeof(string)) ;
}
foreach (GridViewRow row in gvExportCourse.Rows)
{
Label exCourse = (Label)row.FindControl("gvlblCourseName");
Label exUniversityCourse = (Label)row.FindControl("gvlblUniversityCourseName");
if (exCourse != null)
{
if (!string.IsNullOrEmpty(exCourse.Text))
{
TempDataTable.Rows.Add(exCourse.Text, exUniversityCourse.Text);
//TempDataTable is your datatable object. Make sure that datatable contains these columns
}
}
}
}
In Final Save:
protected void button_Click(object s, EventArg e)
{
fnStoreGridData(); //Here this will bind the data of current page
DataTable TempDataTable = new DataTable();
if(Session["Data"]!=null){
TempDataTable = Session["Data"] as DataTable;
}
//Now loop through datatable and store the values
foreach(DataRow in TempDataTable.Rows)
{
CourseInformation course = new CourseInformation();
course.AddCourseMaster(dr["exCourse"].ToString(), dr["exUniversityCourse"].ToString());
}
label1.Text = "Course saved successfully.";
}

How to add and update rows in gridview asp.net

I am doing an online ordering system. I want to check if the item exist in the gridview so it will not add another row or have multiple lines (It will update the qty and the price). The gridview is updating using dgvOrder.Rows[i].Cells[2].Text but my problem is how to update the datatable.
bool isExist = false;
if (Session["dtInSession"] != null)
dt = (DataTable)Session["dtInSession"]; //Getting datatable from session
for (int i = 0; i < dgvOrder.Rows.Count; i++)
{
if (dgvOrder.Rows[i].Cells[0].Text == b.ID)
{
isExist = true;
dgvOrder.Rows[i].Cells[2].Text = Convert.ToString(Convert.ToInt32(dgvOrder.Rows[i].Cells[2].Text) + 1);
dgvOrder.Rows[i].Cells[3].Text = Convert.ToString(Convert.ToInt32(dgvOrder.Rows[i].Cells[2].Text) * price);
}
}
if (!isExist)
{
DataRow dr = dt.NewRow();
dr["pCode"] = b.ID;
dr["desc"] = description;
dr["qty"] = "1";
dr["price"] = price;
dt.Rows.Add(dr);
dgvOrder.DataSource = dt;
dgvOrder.DataBind();
}
Because I am planning to pass the datatable using the session variable.
Session["orders"] = dt;
Response.Redirect("FinalizeOrder.aspx");
after passing the data, the code is working but only 1 qty for each item is passing.
Can anyone help me in this issue?
The problem is that you reload the DataSource of the GridView only if !isExist. Otherwise you are changing the datatable, but you are not assigning it to the GridView again, so the values are coming from the ViewState.
So this should work:
// update the table
// ...
if (!isExist)
{
// ...
}
// reassign the updated DataTable and DataBind the grid always
dgvOrder.DataSource = dt;
dgvOrder.DataBind();

LinkButton in GridView not picking correct value

I am using link button to display a pdf report for selected Report Id from Grid view. On page load I am binding the datasource with Gridview. By clicking the link button it fetches the correct report id from column 0 and displays the report. After sorting the grid the grid view shows the sorted data. Now if i click the link button it is not picking the changed value from column 0. instead it is picking the value before sorted.
Say: Column 0 has values 1, 2, 3, 4, 5 before sorting. If i click link button of Row 3 before sorting it is picking value 3 from column 0. After sorting it is 3,4,5,2,1. Now if i click link button of row 3 it is still picking value 3 instead of 5. Can you please help me.
Below is my code:
aspx:
CS:
protected void Page_Load(object sender, EventArgs e)
{
bindGrid();
}
protected void GvStockTakingReport_Sort(object sender, GridViewSortEventArgs e)
{
GvStockTakingReport.DataSource = null;
GvStockTakingReport.DataBind();
GvStockTakingReport.Dispose();
DataSet ds = StockTakingList.BindStocktakingReportGrid();
DataTable dtSortTable = ds.Tables[0];
if (dtSortTable != null)
{
DataView dv = new DataView(ds.Tables[0]);
dv.Sort = e.SortExpression + " " + getSortDirectionString();
//ViewState["sortExpression"] = e.SortExpression;
//Session["sortExpression"] = e.SortExpression;
GvStockTakingReport.DataSource = dv;
GvStockTakingReport.DataBind();
}
}
protected void PrintReport(object sender, CommandEventArgs e)
{
LinkButton lkButton = (LinkButton)sender;
GridViewRow item = (GridViewRow)lkButton.NamingContainer;
string Id = (item.FindControl("lblstk_id") as Label).Text;
//Getting value for Id
string Id1 = e.CommandArgument.ToString();
int rowIndex = Convert.ToInt32((string)e.CommandArgument);
//string Id1 = Convert.ToString(GvStockTakingReport.Rows[rowIndex].Cells[0].Text);
string Id2 = ((Label)(GvStockTakingReport.Rows[rowIndex].FindControl("lblstk_id"))).Text;
//Getting value for Id
string virtualPath = string.Format("~/{0}/{1}{2}", Portal.Business, Portal.Core.Profile.ReportsDirectory, "General/RPT_03002_StockTakinReport.rpt");
string physicalPath = Server.MapPath(virtualPath);
using (ReportDocument report = new ReportDocument())
{
report.Load(physicalPath);
Core.Security.CrystalReportLogOn(report, (SqlConnectionStringBuilder)Portal.Core.Profile.ConnectionStrings["MTServer"]);
report.SetParameterValue("#STK_Id", Id);
report.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Page.Response, true, "Stock Taking report");
}
}
the issue was whenever i click the link button the page load calls
bindgrid method which resets the gridview to original sorting before the printreport method invokes.
I have included the sorting logic in bindgrid method as well as below which resolved the issue.
public void bindGrid()
{
try
{
DataSet ds = StockTakingList.BindStocktakingReportGrid();
GvStockTakingReport.DataSource = ds;
GvStockTakingReport.DataBind();
//To make sure the grid remains with sorting order while pageload method invokes otherwise it will reset to original order
DataView dv = new DataView(ds.Tables[0]);
if (dv != null)
{
if (ViewState["sortExpression"] == null)
{
ViewState["sortExpression"] = "STK_Id"; //First time it will sort by STK_ID i.e on first time page loading
}
if (ViewState["sortDirection"] == null)
{
ViewState["sortDirection"] = "ASC";//First time it will sort ascending i.e on first time page loading
}
dv.Sort = ViewState["sortExpression"].ToString() + " " + ViewState["sortDirection"].ToString();
GvStockTakingReport.DataSource = dv;
GvStockTakingReport.DataBind();
}
}
catch (Exception ex)
{
error.Visible = true;
error.Text = ex.Message.ToString();
}
}

Drop Down List values in databind

My dropdownlist is set to databine like this...
dt = dal.FillDataTable(SqlConnectionString, "SELECT SQL Query Statement")
dropdownlist1.datasource = dt
dropdownlist1.datatextfield = dt.columns.item(0).tostring
dropdownlist1.databind()
This is turn populates my dropdownlist, when a user selects a value, it is then populated to the remaining textboxes on the remaining forms with a session call...
dropdownlist2.add(ctype(session.item("valOne"), String))
Through this session it populates the one value, is it possible to display the selected value but also include all other dropdownlist items in case they want to change thier selection? Any suggestions would really help?
I didnt understand adding one value at a time. Just show them all the associated values and let them select or change their decision.
Sample code
public DataSet GetmTest_Filter()
{
try
{
DataSet oDS = new DataSet();
SqlParameter[] oParam = new SqlParameter[1];
oParam[0] = new SqlParameter("#col_Id", _scolidvalue);
oDS = SqlHelper.ExecuteDataset(DataConnectionString, CommandType.StoredProcedure, "your_stored_procedure_here", oParam);
return oDS;
}
catch (Exception e)
{
ErrorMessage = e.Message;
return null;
}
}
public void ddlFill_Test(DropDownList ddl)
{
DataSet oDSddlmTest = new DataSet();
oDSddlmTest = GetmTest_Filter();
if (oDSddlmTest.Tables[0].Rows.Count > 0)
{
ddl.DataSource = oDSddlmTest.Tables[0].DefaultView;
ddl.DataTextField = "col_desc";
ddl.DataValueField = "col_id";
ddl.DataBind();
}
else
{
ddl.Enabled = false;
}
}
May this help you.

Resources