asp.net linq query datatable - c#

I have been following this tutorial to implement edit/update functionality via a modal popup form in asp.net:
http://msdnaspdotnettuto.blogspot.com/2015/01/aspnet-gridview-crud-using-twitter.html
This is my code:
public partial class GroupSummary1 : System.Web.UI.Page
{
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGroupSummary();
}
}
private void LoadGroupSummary()
{
try
{
UserBLL userBLL = new UserBLL();
dt = userBLL.GetGroupSummary(2, 2017);
gvGroupSummary.DataSource = dt;
gvGroupSummary.DataBind();
}
catch (SqlException ex)
{
System.Console.Error.Write(ex.Message);
}
}
protected void gvGroupSummary_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName.Equals("detail"))
{
string code = gvGroupSummary.DataKeys[index].Value.ToString();
IEnumerable<DataRow> query = from i in dt.AsEnumerable()
where i.Field<int>("GroupID").Equals(code)
select i;
DataTable detailTable = query.CopyToDataTable<DataRow>();
DetailsView1.DataSource = detailTable;
DetailsView1.DataBind();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script type='text/javascript'>");
sb.Append("$('#detailModal').modal('show');");
sb.Append(#"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "DetailModalScript", sb.ToString(), false);
}
}
}
When I select the "detail" button on the grid view, the following error occurs:
System.ArgumentNullException HResult=0x80004003 Message=Value
cannot be null. Parameter name: source Source= StackTrace:
At this line:
IEnumerable<DataRow> query = from i in dt.AsEnumerable()
where i.Field<int>("GroupID").Equals(code)
select i;
The dt object is NULL and I suspect this is the source of the problem. However, I have declared it above just as in the tutorial.
Any ideas?
Thanks

LoadGroupSummary is only firing on initial page load, not on postback. Clicking your detail button to call gvGroupSummary_RowCommand() will cause a postback.
Simply remove the if (!IsPostBack) from your page load.
protected void Page_Load(object sender, EventArgs e)
{
LoadGroupSummary();
}
EDIT:
Might be worth mentioning that if whatever data userBLL.GetGroupSummary() returns is static, you should probably only load it once. For Example:
private void LoadGroupSummary()
{
try
{
if (Session["GroupSummary"] != null)
{
dt = (DataTable)Session["GroupSummary"];
}
else
{
UserBLL userBLL = new UserBLL();
dt = userBLL.GetGroupSummary(2, 2017);
Session["GroupSummary"] = dt;
}
gvGroupSummary.DataSource = dt;
gvGroupSummary.DataBind();
}
catch (SqlException ex)
{
System.Console.Error.Write(ex.Message);
}
}

Related

Automatic postback: Give error the variable name has already been declared

I'm trying to bind telerik autocomplete textbox from mssql database using asp c#.net.
<telerik:RadAutoCompleteBox AllowCustomEntry="true" ID="RadAutoCompleteBox2" runat="server" InputType="Text">
<TextSettings SelectionMode="Single" />
</telerik:RadAutoCompleteBox>
And my .aspx.cs file's code is given below
protected void Page_Load(object sender, EventArgs e)
{
try
{
SqlDataSource SqlDataSource1 = new SqlDataSource();
SqlDataSource1.ID = "SqlDataSource1";
this.Page.Controls.Add(SqlDataSource1);
SqlDataSource1.ConnectionString = "my connection";
SqlDataSource1.SelectCommand = "select citylocation from citylocationtbl where cityname=#cityname";
SqlDataSource1.SelectParameters.Add("#cityname", Request.QueryString["city"].ToString());
RadAutoCompleteBox2.DataSourceID = "SqlDataSource1";
RadAutoCompleteBox2.DataTextField = "citylocation";
RadAutoCompleteBox2.DataBind();
}
catch (Exception ex)
{
}
}
When I remove Parameters, code working properly but in parameters line I'm still getting error.
The variable name #cityname has already been declared. Variable names must be unique within a query batch or stored procedure.
I'm getting error because when I press any key telerik autosuggesbox automatically postback and bind data again and again.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadCity(Request.QueryString["city"].ToString());
}
}
protected void LoadCity(string _city)
{
try
{
SqlDataSource SqlDataSource1 = new SqlDataSource();
SqlDataSource1.ID = "SqlDataSource1";
this.Page.Controls.Add(SqlDataSource1);
SqlDataSource1.ConnectionString = "my connection";
SqlDataSource1.SelectCommand = "select citylocation from citylocationtbl where cityname=#cityname";
SqlDataSource1.SelectParameters.Add("#cityname", _city);
RadAutoCompleteBox2.DataSourceID = "SqlDataSource1";
RadAutoCompleteBox2.DataTextField = "citylocation";
RadAutoCompleteBox2.DataBind();
}
catch (Exception ex)
{
}
}

Is It Possible to display Employee details in Treeview control

I need help on treeview control. I am using treeview control in my aspx page and binding data from database using store procedure. My output is fine but i have an issue to show employee details side of treeview. I mean if an user clicks an node or value in treeview control i need to display details of selected value in treeview control. Is it possible to create a profile table side of treeview..Please help me to solve the issue.
Below is my code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Username"] == null)
{
Session["Msg"] = "Your session has expired. please login again";
Response.Redirect("../Account/login.aspx");
//.........
return;
}
private void GetTreeViewItems()
{
try
{
string cs = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlDataAdapter da = new SqlDataAdapter("sp_GetEmployee", con);
DataSet ds = new DataSet();
da.Fill(ds);
ds.Relations.Add("ChildRows", ds.Tables[0].Columns["id"], ds.Tables[0].Columns["ManagerId"]);
foreach (DataRow level1DataRow in ds.Tables[0].Rows)
{
if (string.IsNullOrEmpty(level1DataRow["ManagerId"].ToString()))
{
TreeNode parentTreeNode = new TreeNode();
parentTreeNode.Text = level1DataRow["FirstName"].ToString();
// parentTreeNode.Text = level1DataRow["Designation"].ToString();
parentTreeNode.Value = level1DataRow["id"].ToString();
GetChildRows(level1DataRow, parentTreeNode);
TreeView1.Nodes.Add(parentTreeNode);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
private void GetChildRows(DataRow dataRow, TreeNode treeNode)
{
DataRow[] childRows = dataRow.GetChildRows("ChildRows");
foreach (DataRow childRow in childRows)
{
TreeNode childTreeNode = new TreeNode();
childTreeNode.Text = childRow["FirstName"].ToString();
// childTreeNode.Text = childRow["Designation"].ToString();
childTreeNode.Value = childRow["id"].ToString();
treeNode.ChildNodes.Add(childTreeNode);
if (childRow.GetChildRows("ChildRows").Length > 0)
{
GetChildRows(childRow, childTreeNode);
}
}
}
protected void TreeView1_TreeNodeDataBound(object sender, TreeNodeEventArgs e)
{
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
}
Take a look at this
windows form treeview with dynamic child
The answer here will give you an idea how to implement the treeView for employees

Asp.net listview does not display data correctly

My problem is that when i display data in listview for first time then it show correctly but when i display data second time then listview does not update the data correctly. I have made a function for databinding with listview which i have called in pageLoad and some other method.
Can anyone please give me a solution about this ?
I have also uploaded my source code for more detail.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListView();
}
}
protected void LoadDataIntoListView()
{
Users objQuery = new Users();
string adminID = "Here is my query to get the data from MS-SQL";
objQuery.ExecuteSql(str);
if (objQuery.RowCount > 0)
{
Title = "Row affected";
lstAppointments.Items.Clear();
lstAppointments.DataSource = objQuery.DefaultView;
lstAppointments.DataBind();
}
else
{
Title = "None Row affected";
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
string caseID = (string)Session["caseID"];
//string updateQuery = "update Cases set sCaseStatus='cancel' where iCaseID= '" + caseID + "'";
Cases objCases = new Cases();
objCases.LoadByPrimaryKey(Convert.ToInt32(caseID));
if (String.Equals(objCases.SCaseStatus, "cancel"))
{
Page.Title = "No Update";
ModalPopupExtender1.Hide();
}
else
{
objCases.SCaseStatus = "cancel";
objCases.Save();
Page.Title = "No Update";
ModalPopupExtender1.Hide();
lstAppointments.Items.Clear();
LoadDataIntoListView();
}
}
Thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListView();
}
}
You are binding data in not Postback. That means it does not binds data when you postback to same page. If you want to bind that on every page load, call the function LoadDataIntoListView() in Page_Load

Avoid adding blank new rows

I created a grid view application and outside of my template I have a Add new row button. When i add a new row , it gets placed with an Edit and delete button. What I'm trying to do is when I click the add new row button, i want it to open the new row in editing mode, so no blank rows can be added with empty information. So basically if I add a new row and dont input information it wont be created.
If I need to be more thorough on my explanation please ask.
Any help will be appreciated.
Thank you
I ended up figuring out the problem on my own. It works perfect now. I as well changedup the database but I'm providing my code. Im sure there is an easier way but this was the best I could do: If you guys can provide inputs on an easier way I would appreciate it.
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert") //- this is needed to explain that the INSERT command will only work when INSERT is clicked
{
gv.DataBind();
DataTable d = dbcon.GetDataTable("SELECT * FROM CIS.CIS_TRANS ORDER BY ID DESC", "ProjectCISConnectionString");
string transCode = "", fundCode = "", BSA_CD = "", DP_TYPE = "";
if (d.Rows.Count > 0)
{
transCode = d.Rows[0]["TRANS_CD"].ToString();
fundCode = d.Rows[0]["FUND_CD"].ToString();
BSA_CD = d.Rows[0]["BSA_CD"].ToString();
DP_TYPE = d.Rows[0]["DP_TYPE"].ToString();
if (transCode.Trim().Length > 0)
{
dbcon.Execute("INSERT INTO CIS.CIS_TRANS (TRANS_CD) VALUES('')", "ProjectCISConnectionString");
gv.DataBind();
}
}
gv.EditIndex = gv.Rows.Count - 1;
}
else if (e.CommandName == "Cancel")
{
DataTable d = dbcon.GetDataTable("SELECT * FROM CIS.CIS_TRANS ORDER BY ID DESC", "ProjectCISConnectionString");
string transCode = "";
if (d.Rows.Count > 0)
{
transCode = d.Rows[0]["TRANS_CD"].ToString();
if (transCode.Trim().Length == 0)
{
dbcon.Execute(string.Format("DELETE CIS.CIS_TRANS WHERE ID = '{0}'", d.Rows[0]["ID"]), "ProjectCISConnectionString");
gv.DataBind();
}
}
}
}
This is fairly simple, once you add the row:
You need to set the edit index of the newly added row:
gv.EditIndex = gv.Rows.Count-1;
Edit for OP
This is dirty code, I am just showing you what I mean and whipped it up fairly quickly.
Assume a gridview called GridView1 on your page:
namespace HelpSO3
{
public partial class _Default : System.Web.UI.Page
{
List<string> t = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string s = "hi";
t.Add(s);
GridView1.DataSource = t;
GridView1.DataBind();
Session["MyList"] = t;
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
t = (List<string>)Session["MyList"];
t.Add("Another String");
GridView1.DataSource = t;
GridView1.DataBind();
GridView1.EditIndex = GridView1.Rows.Count - 1;
GridView1.DataBind();
Session["MyList"] = t;
}
}
}
So the Button1_Click event adds a new row with the value "Another String" then we bind the grid view and set the EditIndex value to the newest row and rebind. Its that simple.
In your case your code would become:
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert") //- this is needed to explain that the INSERT command will only work when INSERT is clicked
{
dbcon.Execute("INSERT INTO PROJ_ASP (TRANS_CD) VALUES('')", "ProjectASPConnectionString");
gv.DataBind();
gv.EditIndex = gv.Rows.Count-1;
gv.DataBind();
}
}

Deleting 11th row in RadGrid makes it become blank

I have one Telerik RadGrid. Using a method I am filling the grid. I have enabled the paging property. I have used ItemTemplate-->ImageButton for delete and edit options. I have set page size as 10. Page load time is working properly and populating the grid. After inserting the 11th row the pagination starts and it will show in the next page with one record. But when I am deleting the 11th row the grid becomes blank. I have used dataset to bind the records.
radgrid.DataBind();
dsDataset.Dispose();
But its item.count is 0. What is the reason?
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
PopulatePackage();
}
}
catch (Exception ex)
{
lblMessage.Text = objUtl.GetErrorMessage(ex, this);
lblMessage.Visible = true;
protected void gvPackage_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
try
{
SqlHelper objSQL = new SqlHelper();
DataSet dsPackage = new DataSet();
dsPackage = objSQL.ExecuteDataset("AL_PackageType_List_Retrieve", objUtl.NumericEntry(Session["LocationId"].ToString()));
gvPackage.DataSource = dsPackage.Tables[0];
dsPackage.Dispose();
//PopulatePackage();
}
catch (Exception ex)
{
lblMessage.Text = objUtl.GetErrorMessage(ex, this);
lblMessage.Visible = true;
}
}
private void PopulatePackage()
{
try
{
lblMessage.Text = string.Empty;
SqlHelper objSQL = new SqlHelper();
DataSet dsPackage = new DataSet();
dsPackage = objSQL.ExecuteDataset("AL_PackageType_List_Retrieve", objUtl.NumericEntry(Session["LocationId"].ToString()));
gvPackage.DataSource = null;
gvPackage.DataSource = dsPackage.Tables[0];
gvPackage.DataBind();
//dsPackage.Dispose();
if (gvPackage.Items.Count <= 0)
{
lblMessage.Text = "No Package Details Found...";
gvPackage.Visible = false;
}
else
{
gvPackage.Visible = true;
}
}
catch (Exception ex)
{
lblMessage.Text = objUtl.GetErrorMessage(ex, this);
lblMessage.Visible = true;
}
}
Okay as far as I am understanding it, You have a radgrid in which you have allowed paging and set the page size to 10. Upon inserting the 11th record a new page is shown with that 11th record. And when that 11th record is deleted you are viewing a blank page, instead of showing the page having record from 1 to 10. I hope I am right here.
Anyway. I guess the problem is that the Radgrid is not having the data for the page you are viewing now.
There is an event in RadGrid named NeedDataSource. This Event is fired up whenever the RadGrid needs to display the data. You can call the Binding logic in this event and see if it works for you.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
RadGrid1.DataSource = "BindingSource";
RadGrid1.DataBind();
}
protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
BindGrid();
}
See if this works for you..

Categories

Resources