Preventing SQL injection asp.net in C# [closed] - c#

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have been trying to cure this site of SQL injection and a page I have been working on has had me stopped for 2 days.
So far I am validating user input from the client site using. RegularExpressionValidator.
On this page this is the only typed input from the user. There is also a dynamic drop down that is being verified using server-side verification.
Data from the username textbox is also being validated on the client side using Regex.
Initially I converted all of the queries to be parametrized queries. Since I have converted all of the parametrized queries to stored procedures.
Now I am at a loss on where to go next. From searching forums the mix of client-side validation and parametrized queries will generally secure against injection.
I feel like I am missing something here.
Attached is the code for the page as well as the usercontrol in c#. Any direction would be greatly appreciated!
#
<%# Control Language="C#" AutoEventWireup="true" Inherits="EPayment.AdminSite.AssignUsersUC" %>
<script runat="server" type="text/javascript" >
</script>
<div style="float:left;width:120px"><asp:Label ID="UserNameLbl" runat="server" Text="User Logon:" CssClass="label"></asp:Label></div>
<div style="float:left; height: 22px;"><asp:TextBox ID="UserNameTxt" runat="server" OnTextChanged="UserNameTxt_TextChanged"></asp:TextBox>
<asp:RegularExpressionValidator id="RegularExpressionValidator1"
ControlToValidate="userNameTxt"
ValidationExpression="[a-zA-Zs0-9]{1,40}$"
AutoPostBack="true"
Display="Static"
ErrorMessage="Username must contain only Alpha-Numeric Characters"
EnableClientScript="False"
runat="server"/>
<div style="float:left"> <asp:DropDownList ID="ddlcompany" runat="server" AutoPostBack="true" DataTextField="CompanyName" DataValueField="CompanyId" OnSelectedIndexChanged="ddlcompany_SelectedIndexChanged" >
</asp:DropDownList></div>
</div>
<br />
<div style="clear:both"><asp:Label ID="companyLbl" runat="server" Text="Company:" CssClass="label"></asp:Label> </div>
<br />
<div> <asp:Button ID="btngetroles" Text="GetRoles" runat="server" Visible="false" OnClick="btngetroles_Click" /><asp:Button ID="btngetuserobject" Text="GetUserId" runat="server" Visible="false" OnClick="btngetuserobject_Click" /></div>
<div class="sectionRow" style="width:100%;">Roles:
</div>
<br />
<div style="width:600px">
<asp:GridView ID="GV" runat="server" DataKeyNames="RoleId" AutoGenerateColumns="false" Width="100%" ShowHeader="true" ShowFooter="false"
PageSize="100" CellPadding="7">
<HeaderStyle CssClass="gridHdr" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox id="CheckBox2" runat="server" AutoPostBack="True" ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Role Description" >
<ItemTemplate >
<%#
DataBinder.Eval(Container.DataItem, "RoleDesc").ToString().Trim()
%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<br />
<div style="float:left;width:120px"><asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
<asp:Button ID="btnReset" runat="server" Text="Reset" OnClick="btnReset_Click" />
</div>
<div>
<asp:Label ID="Result" runat="server" ForeColor="red"></asp:Label></div>
#
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using EPayment.DatabaseConnectors;
using EPayment.DataObjects;
using EPayment.Common;
using ESource.Security;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using ESource.Installation;
namespace EPayment.AdminSite
{
public partial class AssignUsersUC : System.Web.UI.UserControl
{
private string ConnectionString;
protected SYUserConnector syuserconnector;
protected SYTaskConnector sytaskconnector;
protected SYRoleConnector syroleconnector;
protected SYTask sytask;
protected SYUser syuser;
protected SYRole syrole;
protected SYUtility syutility;
private DBConnString dbconn;
private string dbFilePath;
private string logFilePath;
protected TextBox UserNameTxt;
protected DropDownList ddlcompany;
protected GridView GV;
//protected TextBox UserIdtxt;
protected Label Result;
private MerchantDBConnector mConnector;
private InstallationManager dbReg;
protected void Page_Load(object sender, EventArgs e)
{
UserNameTxt.AutoPostBack = true;
syuserconnector = new SYUserConnector();
syuserconnector.SetConnection(ConnectionString);
syroleconnector = new SYRoleConnector();
syroleconnector.SetConnection(ConnectionString);
sytaskconnector = new SYTaskConnector();
sytaskconnector.SetConnection(ConnectionString);
syutility = new SYUtility();
syutility.SetConnection(ConnectionString);
syuser = new SYUser();
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt = syutility.GetSYCompanies();
ddlcompany.DataSource = dt;
ddlcompany.DataBind();
ArrayList companies = mConnector.GetGPCompanyIds();
foreach (string[] company in companies)
{
ddlcompany.SelectedIndex = -1;
ddlcompany.Items.FindByText(company[1]);
//Context.Response.Write(ddlcompany.SelectedItem.Text + "<br>");
//Context.Response.Write("Before:" + company[1] + "<br>");
//Context.Response.Write("Before Company ID:" + company[0] + "<br>");
if (ddlcompany.SelectedItem.Text.Trim() == company[1].Trim())
{
//Context.Response.Write("if:" + ddlcompany.SelectedItem.Text.Trim() + "<br>");
//Context.Response.Write("Company Name:" + company[1] + "<br>");
//Context.Response.Write("Company ID:" + company[0] + "<br>");
}
else
{
//Context.Response.Write("else:" + ddlcompany.SelectedItem.Text.Trim() + "<br>");
//Context.Response.Write("Company ID:" + company[0] + "<br>");
DBConnString epConn = new DBConnString(logFilePath, dbFilePath);
dbReg.InsertGPCompanyIntoSYCompany(epConn.StrGPServer, epConn.StrGPUser, epConn.StrGPPass, ConfigurationManager.AppSettings["EPaymentDBName"], company[0], company[1]);
//ddlcompany.Items.Add(new ListItem(company[1], company[0]));
dt = syutility.GetSYCompanies();
ddlcompany.Items.Clear();
ddlcompany.DataSource = dt;
ddlcompany.DataBind();
}
}
//ddlcompany.Items.Insert(0, new ListItem("ViewAll", "ViewAll"));
string companyname = ConfigurationManager.AppSettings["EPaymentCompanyERPId"];
string companyID = syutility.GetCompanyId(companyname);
DataView dv = new DataView();
dv = syroleconnector.GetAllRoles(companyID, 0);
GV.DataSource = dv;
GV.DataBind();
}
}
protected void btngetroles_Click(object sender, EventArgs e)
{
}
protected void ddlcompany_SelectedIndexChanged(object sender, EventArgs e)
{
Getroles();
}
protected void Page_UnLoad(object sender, EventArgs e)
{
syuserconnector.CloseConnection();
syroleconnector.CloseConnection();
sytaskconnector.CloseConnection();
syutility.CloseConnection();
syuserconnector = null;
syroleconnector = null;
sytaskconnector = null;
syutility = null;
syuser = null;
}
private void Page_Init(System.Object sender, System.EventArgs e) //Handles page_init event
{
string serverPath = Request.PhysicalApplicationPath;
dbFilePath = serverPath + "include\\dbconn.txt";
logFilePath = serverPath + "logs\\azoxlog.txt";
dbconn = new DBConnString(logFilePath, dbFilePath);
ConnectionString = dbconn.StrEPConnString;
MerchantAccount m = new MerchantAccount();
mConnector = new MerchantDBConnector(dbFilePath, logFilePath, m);
dbReg = new InstallationManager();
dbReg.UseLogFile = true;
dbReg.LogFilePath = logFilePath;
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
syuser = new SYUser();
//Regex r = new Regex("^[a-zA-Z0-9]*$");
//if (r.IsMatch(UserNameTxt.Text.Trim()))
//{
string username = UserNameTxt.Text;
string companyID = ddlcompany.SelectedItem.Value;
ArrayList companies = mConnector.GetGPCompanyIds();
//bool found = companies.Contains(companyID);
//if (found == true)
//{
string userid = syuserconnector.GetUserId(username, companyID);
if (userid != null && userid != "")
{
Result.Text = "";
//string userId = UserIdtxt.Text;
Collection<string> idsList = new Collection<string>();
foreach (GridViewRow row in GV.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("CheckBox2");
if (chk != null && chk.Checked)
{
string secId = GV.DataKeys[row.RowIndex].Value.ToString();
idsList.Add(secId);
//Response.Write("TaskId: " +secId + "<br/>");
//Response.End();
}
}
syuserconnector.UpdateUserRoles(userid, idsList);
//Start Check if user is given access to BatchProcess and add user to ep database so that sql user has access to EP_BatchReport table which is public
UserDBConnector userConn = new UserDBConnector(dbFilePath, logFilePath, new EPayment.DataObjects.User());
userConn.CreateUserLogOnForBatchReportAccess(UserNameTxt.Text);
//End
Result.Text = "Roles are Assigned to the User";
}
else
{
Result.Text = "";
syuser = new SYUser();
syuser.UserName = UserNameTxt.Text;
string companyname = ddlcompany.SelectedItem.Text;
companyID = ddlcompany.SelectedItem.Value;
syuser.CompanyId = companyID;
syuser.StoreId = 0;
syuser.CreatedBy = Session["userLogon"].ToString();
syuser.ExpireDate = DateTime.Now;
userid = syuserconnector.SaveUser(syuser);
//UserIdtxt.Text = userid;
if (userid != null && userid != "")
{
//string userId = UserIdtxt.Text;
Collection<string> idsList = new Collection<string>();
foreach (GridViewRow row in GV.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("CheckBox2");
if (chk != null && chk.Checked)
{
string secId = GV.DataKeys[row.RowIndex].Value.ToString();
idsList.Add(secId);
//Response.Write("TaskId: " +secId + "<br/>");
//Response.End();
}
}
syuserconnector.UpdateUserRoles(userid, idsList);
Result.Text = "User is Added and Roles are assigned to the User";
}
//}
//}
}
}
//else
//{
// Result.Text = "Username can only contain alpha-numeric characters. ";
//}
}
protected void btnReset_Click(object sender, EventArgs e)
{
resetAllFields();
}
private void resetAllFields()
{
//UserIdtxt.Text = "";
UserNameTxt.Text = "";
Result.Text = "";
ddlcompany.SelectedIndex = ddlcompany.Items.IndexOf(ddlcompany.Items.FindByValue("E-Payment"));
foreach (GridViewRow row in GV.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("CheckBox2");
chk.Checked = false;
}
}
protected void btngetuserobject_Click(object sender, EventArgs e)
{
}
public void Getroles()
{
if (ValidatePage() == true)
{
Page.Validate();
if (Page.IsValid)
{
string companyID = ddlcompany.SelectedItem.Value;
//ArrayList companies = mConnector.GetGPCompanyIds();
//bool found = companies.Contains(companyID);
//if (found == true)
//{
Result.Text = "";
syuserconnector.UseLogFile = true;
syuserconnector.LogFilePath = Request.PhysicalApplicationPath + "logs\\azoxlog.txt";
Collection<string> idsList = new Collection<string>();
string companyname = ddlcompany.SelectedItem.Text;
companyID = ddlcompany.SelectedItem.Value;
// string ERPcompanyId;
//string companyID = "";
//if (companyname == "Fabrikam Inc")
//{
// ERPcompanyId = "-1";
// companyID = syutility.GetCompanyId(ERPcompanyId);
//}
//else
//{
// string companyID = syutility.GetCompanyId(companyname);
//}
//Response.Write(companyID);
Regex r = new Regex("[a-zA-Z]{1,40}");
string userid;
string username = UserNameTxt.Text;
if (username != null && r.IsMatch(UserNameTxt.Text.Trim()))
{
foreach (GridViewRow row in GV.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("CheckBox2");
chk.Checked = false;
}
userid = syuserconnector.GetUserId(username, companyID);
//UserIdtxt.Text = userid;
// Response.Write("Test:" + userid);
if (userid != null && userid != "")
{
syuser = new SYUser();
syuser = syuserconnector.GetUserObject(userid);
idsList = syuser.RoleIds;
foreach (GridViewRow row in GV.Rows)
{
string rolegv = GV.DataKeys[row.RowIndex].Value.ToString();
// Response.Write(securitygv + "<br>");
CheckBox chk = (CheckBox)row.FindControl("CheckBox2");
if (syuser.RoleIds.Contains(rolegv))
{
chk.Checked = true;
}
}
}
else
{
foreach (GridViewRow row in GV.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("CheckBox2");
chk.Checked = false;
}
Result.Text = "User not in any roles for " + companyname;
}
}
//else
// {
// Result.Text = "Enter Username";
// }
//}
}
}
}
protected void UserNameTxt_TextChanged(object sender, EventArgs e)
{
//string Username = UserNameTxt.Text;
//resetAllFields();
//UserNameTxt.Text = Username;
//Page.Validate();
//if (Page.IsValid)
//{
if (ValidatePage() == true)
{
//Regex r = new Regex("[a-zA-Z0-9]*$");
//if (r.IsMatch(UserNameTxt.Text.Trim()))
//{
Getroles();
//}
}
}
protected bool ValidatePage()
{
Page.Validate();
if (Page.IsValid)
{
Regex r = new Regex("[a-zA-Z0-9]");
if (r.IsMatch(UserNameTxt.Text.Trim()))
{
return true;
}
return false;
}
return false;
}
}
}

Initially I converted all of the queries to be parametrized queries. Since I have converted all of the parametrized queries to stored procedures.
Good. Now your code is (already) safe from SQL Injection attacks. This only means that the SQL commands are "safe" from having their structure altered. However, it does not ensure that the data is valid: data-validity is determined by business rules.
Now, the client should not be trusted so, always perform data validation on the back-end. This may be in the database (constraints, triggers) or DAL or some ORM or even just the ASP code-behind (e.g. "validators"). Additionally, validation can be performed on the front-end (e.g. JavaScript); this, however, is just a "first line of defense" and a way of giving the user more useful information. Some libraries/frameworks (e.g. WCF RIA) allow a "unified" way of describing these business rules.
In any case -- it's no longer an issue of an "injection attack" so much as defining what valid data is and preventing invalid data from being accepted. (Also note that how the data is consumed later is important.)

Ok...Sql injection can be done when your application is making database calls via sql that is formed as a result of concatenated text...instead you need to use parametrized querying...
Avoid creating sql as below:
string sql = "Select * from Customer where Name = " + txtName.Text;
Instead use Parameterized queries...something like
"Select * from Customer where Name = #Name"
Hope this helps...

Related

ASP .net datagrid sometimes show empty rows, without text

ASP. net data grid show empty rows without text randomly. Though is shows empty rows, on double clicking on empty row, the data from the row gets populated correctly to another text box.
Below is the UI code.
<asp:Panel ID="pnlDataControl" runat="server" Enabled="true" EnableViewState="true">
<div class="grdCtl">
<asp:GridView ID="grdlDataControl" runat="server" ShowFooter="True"
AutoGenerateColumns="False" GridLines="None" AllowPaging="True" AllowSorting="True"
Width="100%" BorderColor="Red" BorderWidth="0px" BorderStyle="Solid" EmptyDataText=""
onpageindexchanging="grdlDataControl_PageIndexChanging"
ondatabound="grdlDataControl_DataBound"
onrowdatabound="grdlDataControl_RowDataBound"
onselectedindexchanged="grdlDataControl_SelectedIndexChanged"
onrowcommand="grdlDataControl_RowCommand" style="margin-bottom: 18px;">
<SelectedRowStyle BackColor="Gray" Font-Bold="true" />
<Columns>
<asp:TemplateField HeaderStyle-CssClass="grdHead" HeaderStyle-Wrap="false" ItemStyle-CssClass="" HeaderStyle-Width="10px" ItemStyle-Width="10px">
<ItemTemplate></ItemTemplate>
<HeaderTemplate></HeaderTemplate>
<HeaderStyle CssClass="grdHead" Width="10px" Wrap="False" />
<ItemStyle Width="10px" />
</asp:TemplateField>
</Columns>
<EmptyDataRowStyle HorizontalAlign="Center" />
<FooterStyle />
</asp:GridView>
</div>
</asp:Panel>
<br/>
</ContentTemplate>
</asp:UpdatePanel>
Attached is the screenshot how the results are populated in the datagrid.empty rows
Code behind
private void fntLoadData()
{
try
{
mLocationData = (IEnumerable<clsLocationData>)Session["DataRecords"];
if (mLocationData != null) mDataTotalRecords = mLocationData.Count();
this.grdlDataControl.DataSource = mLocationData;
this.grdlDataControl.DataBind();
if(clsApplication.LDSCount>=clsApplication.cParamMaximumResult)
{
Label ctlLabel = (Label)grdlDataControl.BottomPagerRow.FindControl("lblAlert");
ctlLabel.Text = fntGetLanguageValue("MoreRecords", "MESSAGES", "OR").Replace("1%", clsApplication.cParamMaximumResult.ToString());
}
}
catch (Exception ex)
{
fntCatchError(ex,"fntLoadData():");
}
}
protected void grdlDataControl_DataBound(object sender, EventArgs e)
{
GridViewRow gvrPager = grdlDataControl.BottomPagerRow;
if (gvrPager == null) return;
DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");
Label txtPages = (Label)gvrPager.Cells[0].FindControl("txtPages");
Label lblPages = (Label)gvrPager.Cells[0].FindControl("lblPages3");
// populate dropdownlist
if (ddlPages != null)
{
for (int i = 0; i < grdlDataControl.PageCount; i++)
{
int intPageNumber = i + 1;
ListItem lstItem = new ListItem(intPageNumber.ToString());
if (i == grdlDataControl.PageIndex) lstItem.Selected = true;
ddlPages.Items.Add(lstItem);
}
}
if (txtPages != null) txtPages.Text = grdlDataControl.PageCount.ToString();
if (lblPages != null) lblPages.Text = "(" + mDataTotalRecords + " " + fntGetLanguageValue("lblItems", "LABEL", "OR") + ")";
// Check for next, prev images status
ImageButton btnFrst = (ImageButton)gvrPager.Cells[0].FindControl("btnPagerFrst");
ImageButton btnPrev = (ImageButton)gvrPager.Cells[0].FindControl("btnPagerPrev");
ImageButton btnNext = (ImageButton)gvrPager.Cells[0].FindControl("btnPagerNext");
ImageButton btnLast = (ImageButton)gvrPager.Cells[0].FindControl("btnPagerLast");
if (grdlDataControl.PageIndex == 0)
{
btnPrev.Enabled = false; //btnPrev.ImageUrl = "./Images/icon_prev_i.gif";
btnFrst.Enabled = false; //btnFrst.ImageUrl = "./Images/icon_frst_i.gif";
}
else if (grdlDataControl.PageIndex + 1 == grdlDataControl.PageCount)
{
btnLast.Enabled = false; //btnLast.ImageUrl = "./Images/icon_last_i.gif";
btnNext.Enabled = false; //btnNext.ImageUrl = "./Images/icon_next_i.gif";
}
else
{
btnLast.Enabled = true; //btnLast.ImageUrl = "./Images/icon_last.gif";
btnNext.Enabled = true; //btnNext.ImageUrl = "./Images/icon_Next.gif";
btnPrev.Enabled = true; //btnPrev.ImageUrl = "./Images/icon_Prev.gif";
btnFrst.Enabled = true; //btnFrst.ImageUrl = "./Images/icon_frst.gif";
}
}
protected void grdlDataControl_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (clsApplication.cDataDisplayTypIcon == "true")
{
string sSymbol = ((clsLocationData)(e.Row.DataItem)).sTYPE;
System.Web.UI.WebControls.Image ImgIcon = new System.Web.UI.WebControls.Image();
string iconPath = "./Images/#" + sSymbol + ".gif";
string iconFile = "./Images/#NOTYPE.gif";
if (fntIsValidImage(Server.MapPath(iconPath))) iconFile = iconPath;
ImgIcon.ImageUrl = iconFile;
ImgIcon.Width = 16; ImgIcon.Height = 16; ImgIcon.ImageAlign = ImageAlign.AbsMiddle; ImgIcon.CssClass = "grdLocationIcon";
e.Row.Cells[0].Controls.Add(ImgIcon);
}
if (mDateRelevanceIdx > 0)
{
e.Row.Cells[mDateRelevanceIdx].Controls.Clear();
Double dRelevance = ((clsLocationData)(e.Row.DataItem)).sRELEVANCE;
if (clsApplication.cDataDisplayRelvBar == "true")
{
string sBarCSS = "grdRelevenceBar1";
if (dRelevance > 10) sBarCSS = "grdRelevenceBar2";
if (dRelevance > 20) sBarCSS = "grdRelevenceBar3";
if (dRelevance > 30) sBarCSS = "grdRelevenceBar4";
int iBarWidth = 40;
if (dRelevance > 10) iBarWidth = 30;
if (dRelevance > 20) iBarWidth = 20;
if (dRelevance > 30) iBarWidth = 10;
Label LabelBar = new Label();
//LabelBar.Width = new Unit((100 - dRelevance)/2);
LabelBar.Width = new Unit(iBarWidth);
LabelBar.CssClass = sBarCSS;
e.Row.Cells[mDateRelevanceIdx].Controls.Add(LabelBar);
}
if (clsApplication.cDataDisplayRelvTxt == "true")
{
Label LabelTxt = new Label();
LabelTxt.Text = (100 - dRelevance).ToString();
e.Row.Cells[mDateRelevanceIdx].Controls.Add(LabelTxt);
}
}
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.className='grdRowHigh';");
e.Row.Attributes.Add("onmouseout", "this.className='grdRowNorm';");
string sArgsData1 = "Select$" + e.Row.RowIndex.ToString();
e.Row.Cells[0].Attributes.Add("onclick", Page.ClientScript.GetPostBackClientHyperlink(grdlDataControl, sArgsData1));
string sArgsData2 = "DblSelect$" + e.Row.RowIndex.ToString();
e.Row.Attributes.Add("Ondblclick", Page.ClientScript.GetPostBackClientHyperlink(grdlDataControl, sArgsData2));
}
}
protected void grdlDataControl_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdlDataControl.PageIndex = e.NewPageIndex;
grdlDataControl.SelectedIndex = -1;
fntLoadDataControl();
}
protected void grdlDataControl_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select" || e.CommandName == "DblSelect")
{
GridView grdData = (GridView)sender;
int iRowIndex = int.Parse(e.CommandArgument.ToString());
int iPageIndex = grdData.PageIndex;
int iRowNumber = clsApplication.cDataRecordPerPage * iPageIndex + iRowIndex;
fntLoadDataControl();
if (e.CommandName == "DblSelect")
{
fntGetRowDataItem(iRowNumber, "dclick");
}
if (e.CommandName == "Select") fntGetRowDataItem(iRowNumber, "sclick");
}
this.grdlDataControl.DataBind();
}
void btnCtl_Click(object sender, EventArgs e)
{
Button btnCtl = (Button)sender;
mDataRecordSortFld = btnCtl.CommandName;
mDataRecordSortOrd = btnCtl.CommandArgument;
mDataRecordSortOrd = fntGetSortOrder(mDataRecordSortFld, mDataRecordSortOrd);
grdlDataControl.SelectedIndex = -1;
fntSortDataControl();
fntLoadDataControl();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
grdlDataControl.PageIndex = 0;
grdlDataControl.SelectedIndex = -1;
Session["DataRecords"] = null;
fntGetLocationData(false, null);
}
private void fntGetLocationData(bool isLocVer, EMEALVINTERFACE.LocationData LocData)
{
XmlDocument xmlLocation = oLV.GetLocationData(isLocVer,LocData);
fntLoadXML(xmlLocation);
}
private void fntLoadXML(XmlDocument xmlDocument)
{
try
{
if (xmlDocument != null && xmlDocument.InnerXml != "")
{
XDocument xDoc = XDocument.Parse(xmlDocument.InnerXml);
// IEnumerable<clsLocationData> vLocations = null;
var vLocations = from location in xDoc.Descendants("LOCATION")
select new clsLocationData
{
//copy locations
};
mLocationData = (IEnumerable<clsLocationData>)vLocations.ToList();
mLocationData = fntSortData(mLocationData, mDataRecordSortFld, mDataRecordSortOrd);
Session["DataRecords"] = mLocationData.ToList();
}
else
{
Session["DataRecords"] = null;
}
}
catch (Exception ex)
{
fntCatchError(ex,"fntLoadXML():");
}
}
Also, this application is being used by many remote clients and it is hosted on IIS in a server.
Make sure the global variable mLocationData is not being altered elsewhere in the code. It seems that either this variable, or Session["DataRecords"] is being reset elsewhere.
If the page loads correctly the first time the page loads, and the records disappear on subsequent postbacks, that points to the datasource being altered.

Adding a dropdown list from server side

i have this following code :
<asp:DropDownList ID="dd_SubCategory" Width="160px" runat="server" DataTextField="CATEGORY_NAME" DataValueField="CATEGORY_ID"></asp:DropDownList>
<br />
<asp:Panel ID="pnl_SubCatg" runat="server"></asp:Panel>
<asp:ImageButton ID="Ib_AddSubCategory" runat="server" OnClick="Ib_AddSubCategory_Click" ImageUrl="/images/add.gif" />
protected void Ib_AddSubCategory_Click(object sender, ImageClickEventArgs e)
{
string SelectedCategory="";
if (ctrl_list.Count == 0)
SelectedCategory = dd_SubCategory.SelectedValue;
else
SelectedCategory = Session["Selected_SubCatg"] != null && Session["Selected_SubCatg"].ToString()!=""?Session["Selected_SubCatg"].ToString():((DropDownList)ctrl_list[ctrl_list.Count - 1]).SelectedValue;
try
{
DataRow[] Rows = DataHelper.TicketCategories.Select("PARENT_CATEGORY_ID='" + SelectedCategory + "'");
if (Rows.Length > 0)
{
AddSubCategory(Rows);
}
foreach (Control item in ctrl_list)
pnl_SubCatg.Controls.Add(item);
}
catch (Exception ex)
{ }
}
List<Control> _ctrl_list = null;
List<Control> ctrl_list {
get
{
if (Session["SUB_CATG_LIST"] == null)
{
_ctrl_list = new List<Control>();
Session["SUB_CATG_LIST"] = _ctrl_list;
}
return Session["SUB_CATG_LIST"] as List<Control>;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["SUB_CATG_LIST"] = null;
Session["Selected_SubCatg"] = null;
}
if (ctrl_list.Count > 0)
{
foreach (Control item in ctrl_list)
pnl_SubCatg.Controls.Add(item);
}
}
private void AddSubCategory(DataRow [] Rows)
{
DropDownList dd_SubCategory1 = new DropDownList();
dd_SubCategory1.Width = Unit.Pixel(160);
dd_SubCategory1.DataTextField = "CATEGORY_NAME";
dd_SubCategory1.DataValueField = "CATEGORY_ID";
dd_SubCategory1.ID = Guid.NewGuid().ToString();
dd_SubCategory1.DataSource = Rows.CopyToDataTable();
dd_SubCategory1.DataBind();
dd_SubCategory1.SelectedIndexChanged += dd_SubCategory1_SelectedIndexChanged;
dd_SubCategory1.AutoPostBack = true;
ctrl_list.Add(dd_SubCategory1);
}
void dd_SubCategory1_SelectedIndexChanged(object sender, EventArgs e)
{
Session["Selected_SubCatg"] = ((DropDownList)sender).SelectedValue;
}
i am trying to add a dropdown list containing the subcategories of the last inserted dropdown list , my problem is dd_SubCategory1_SelectedIndexChanged is not firing and i can't get the and the selectedValue of the last dropdownlist is always the same
That is because its dynamically generated and it will lose its state after its rendered on your page.
To access the dropdown and its related events and properties, you will need to recreate it everytime your page is postback.
Hope its clear enough.

Grid View doesn't appear at screen

why My GridView was not displaying?
ascx CODE:
<asp:PlaceHolder ID="plcGridTest" runat="server">
<asp:GridView ID="grdTest" runat="server" AutoGenerateColumns="false"/>
</asp:PlaceHolder>
ascx.cs CODE:
protected void btnPesquisar_Click(object sender, EventArgs e)
{
string placa = string.Empty;
insereParameterPlaca(txtPlaca.Text.ToUpper(), out placa);
string transportadora = string.Empty;
transportadora = insereTransportadoraSelecionada();
string tiposWorkflow = string.Empty;
insereTiposWorkflow(chkBox_TiposOcorrencia.Items, out tiposWorkflow);
string cliente = string.Empty;
insereCliente(out cliente);
string query = string.Empty;
query = string.Format(SQL_GET_OCORRENCIAS_PARAMETRIZADO, placa, transportadora, tiposWorkflow, cliente);
using (var sqlDataAccess = new MSQLDataAccess(Util.GetIntegraConnectionString))
{
var datatable = sqlDataAccess.GetDataTable(query);
grdTest.Visible = true;
grdTest.DataSource = datatable;
grdTest.DataBind();
}
}
AutoGenarateColuns was marked as false and I'm runnig DataBind() command.
You should set AutoGenerateColumns="True", if you don't want to specify each column.

How to temporarily store DataTable after Binding

I have two GridViews in which I populate Data on PageStart from database. When I refresh the page (on Post Back), I could not see the datatable content. so I thought of Databinding the GridView again on every pageload. In order to bind the Data I need to store the Data somewhere temporarily. Which one is the Best method to store data temporarily?
In my First Grid there are about 10 rows and in the Second GridView I have about 200 rows. and I'm not using Paging
Here's a fully working sample using ViewState but you can change it for other caching methods.
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView runat="server" ID="gvProd" AutoGenerateColumns="false" OnRowDataBound="gvProd_RowDataBound" OnRowCommand="gvProd_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<asp:Literal runat="server" ID="litNm"></asp:Literal>
<asp:DropDownList runat="server" ID="ddlQty"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Add To Cart">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbnAdd" Text="Add To Cart" CommandName="AddToCart"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<hr />
<asp:GridView runat="server" ID="gvCart" AutoGenerateColumns="false" OnRowDataBound="gvCart_RowDataBound" OnRowCommand="gvCart_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Literal runat="server" ID="litNm"></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" ID="txtQty"></asp:TextBox>
<asp:Button runat="server" ID="btnUpdate" Text="Update Qty" CommandName="UpdateCart" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
[Serializable]
public class Product
{
public int PID { get; set; }
public string Name { get; set; }
public Product(int i) { this.PID = i; this.Name = "product " + i.ToString(); }
}
[Serializable]
public class CartItem
{
public Product Prod { get; set; }
public int Qty { get; set; }
public CartItem(Product p, int q) { this.Prod = p; this.Qty = q; }
}
public List<CartItem> myCart = new List<CartItem>();
public List<CartItem> MyCart
{
get
{
if (ViewState["cart"] == null)
{
ViewState["cart"] = new List<CartItem>();
}
return ViewState["cart"] as List<CartItem>;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindProdGrid();
}
protected void BindProdGrid()
{
gvProd.DataSource = GetProducts();
gvProd.DataBind();
}
protected List<Product> GetProducts()
{
var ret = new List<Product>();
ret.Add(new Product(1));
ret.Add(new Product(2));
return ret;
}
protected void gvProd_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
var row = (e.CommandSource as LinkButton).NamingContainer as GridViewRow;
var ddl = row.FindControl("ddlQty") as DropDownList;
var qty = Convert.ToInt32(ddl.SelectedValue);
var pid = Convert.ToInt32(e.CommandArgument);
AddToCart(pid, qty, increase: true);
BindCartGrid(this.MyCart);
}
}
protected void AddToCart(int pid, int qty, bool increase = false)
{
var cartItem = this.MyCart.Find(o => o.Prod.PID == pid);
if (cartItem == null)
this.MyCart.Add(new CartItem(new Product(pid), qty));
else
if (increase)
cartItem.Qty += qty;
else
cartItem.Qty = qty;
}
protected void gvProd_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var item = e.Row.DataItem as Product;
var litNm = e.Row.FindControl("litNm") as Literal;
litNm.Text = item.Name;
var ddlQty = e.Row.FindControl("ddlQty") as DropDownList;
ddlQty.Items.Add(new ListItem("1", "1"));
ddlQty.Items.Add(new ListItem("10", "10"));
var lbnAdd = e.Row.FindControl("lbnAdd") as LinkButton;
lbnAdd.CommandArgument = item.PID.ToString();
}
}
protected void BindCartGrid(List<CartItem> items)
{
gvCart.DataSource = items;
gvCart.DataBind();
}
protected void gvCart_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var item = e.Row.DataItem as CartItem;
var litNm = e.Row.FindControl("litNm") as Literal;
litNm.Text = item.Prod.Name + " (pid:" + item.Prod.PID.ToString() + ")";
var txtQty = e.Row.FindControl("txtQty") as TextBox;
txtQty.Text = item.Qty.ToString();
txtQty.Attributes["data-pid"] = item.Prod.PID.ToString();
}
}
protected void gvCart_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "UpdateCart")
{
var row = (e.CommandSource as Button).NamingContainer as GridViewRow;
var txtQty = row.FindControl("txtQty") as TextBox;
var qty = Convert.ToInt32(txtQty.Text);
var pid = Convert.ToInt32(txtQty.Attributes["data-pid"]);
AddToCart(pid, qty, increase: false);
BindCartGrid(this.MyCart);
}
}
}
}
Usage of Cache object vs Session again will depend upon whether you want the data to be stored temporarily per session or for all the sessions you want to store the same data.
Session can be used if you want the same data to be maintained only for a particular session of your application.
Cache can be used for all the user sessions across your application.
The best place to store the data will be sessions. Viewstate will bring all the data on client side which is an undesirable network/bandwidth overhead.
your PageStart should look like this:
public void PageStart()
{
if(Session["dt"] == null || !(Session["dt"] is datatable)){
datatable dt;
///your dt populating code
Session["dt"] = dt;
}
yourGridView.datasource = (datatable)Session["dt"];
yourGridView.databind();
}
To address data persistence between postbacks you have several options. I am really against ViewState except in very specific cases where you have a very little amount of data (that's where Microsoft fail in WebForms - its default behaviour is DemoWare).
I would suggest keeping your data in a Cache object and upon postback, read it from that object. But it really depends on your specific use case. There are different techniques.
This is all what you need to do.
Place you method or function which fills the gridview with data like this.
private void FillGrid()
{
DataTable dt = new DataTable();
dt = //Fill you datatable
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
This is what you gotta do on pageload event.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.FillGrid();
}
}

sorting in listview using asp.net C#

i want to do sorting in the listview from code behind, and i have done it by below code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindLV("");
}
public DataTable GetEmployee(string query)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
SqlDataAdapter ada = new SqlDataAdapter(query, con);
DataTable dtEmp = new DataTable();
ada.Fill(dtEmp);
return dtEmp;
}
private void BindLV(string SortExpression)
{
string UpdateQuery = "Select * from Employee" + SortExpression;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
lvEmployee.DataSource = GetEmployee(UpdateQuery);
lvEmployee.DataBind();
}
protected void lvEmployee_Sorting(object sender, ListViewSortEventArgs e)
{
ImageButton imEmpID = lvEmployee.FindControl("imEmpID") as ImageButton;
ImageButton imEmpName = lvEmployee.FindControl("imEmpName") as ImageButton;
string DefaultSortIMG = "~/img/asc.png";
string imgUrl = "~/img/desc.png";
if (ViewState["SortExpression"] != null)
{
if (ViewState["SortExpression"].ToString() == e.SortExpression)
{
ViewState["SortExpression"] = null;
imgUrl = DefaultSortIMG;
}
else
{
ViewState["SortExpression"] = e.SortExpression;
}
}
else
{
ViewState["SortExpression"] = e.SortExpression;
}
switch (e.SortExpression)
{
case "EmpID":
if (imEmpName != null)
imEmpName.ImageUrl = DefaultSortIMG;
if (imEmpID != null)
imEmpID.ImageUrl = imgUrl;
break;
case "EmpName":
if (imEmpID != null)
imEmpID.ImageUrl = DefaultSortIMG;
if (imEmpName != null)
imEmpName.ImageUrl = imgUrl;
break;
}
BindLV(" order by " + e.SortExpression + " " + ((ViewState["SortExpression"] != null) ? "ASC" : "DESC"));
}
but the problem is i'm using another function for data paging as below in code behind which is contain of sorting as well:
protected void DataPager1_PreRender(object sender, EventArgs e)
{
lvEmployee.DataSource = GetEmployee("Select * from Employee");
lvEmployee.DataBind();
}
and my data pager code which is located at LayoutTemplate in .aspx page:
<asp:DataPager ID="DataPager1" runat="server" PagedControlID="lvEmployee" PageSize="5" onprerender="DataPager1_PreRender">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="true" ShowLastPageButton="true"/>
</Fields>
</asp:DataPager>
Every time i click at the name to sort it, there will be no change in the list. E have traced the problem, and I have found out that the sorting function is working properly. But before the page come up, the DataPager1_PreRender function is called and again shows the list without sorting.
Could you please guide me how to do sorting and dataPaging together without this problem. Appreciate your consideration.
I have over come to this problem by using Session.
before i use session i found out every time i press the next page or anytime the page refresh it will execute the DataPager1_PreRender() and i have set the data source to
GetEmployee("Select * from Employee");
that's why the sorting never happens.
i have add Session["UpdateQT"] = UpdateQuery; to BindLV() to keep the update query and i have change the DataPager1_PreRender() to
string strtmp = Session["UpdateQT"].ToString();
if (strtmp == null)
{
strtmp = "Select * from Employee";
}
lvEmployee.DataSource = GetEmployee(strtmp);
lvEmployee.DataBind();
to keep the latest query after sorting.
i hope it helps somebody.

Categories

Resources