I'm trying here to fill dataTable from csv file. But when I'll bind it dataTable to GridView, gridview is empty. Any idea where I'm wrong? Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
bool isFirstRowHeader = true;
string path = System.IO.Path.GetFullPath(#"D:\WebApplication10\WebApplication10\Students.csv");
string header = isFirstRowHeader ? "Yes" : "No";
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
string sql = #"SELECT * FROM [" + fileName + "]";
using (OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
using (OleDbCommand command = new OleDbCommand(sql, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
dt.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dt);
//if (dt.Rows.Count > 0)
//{
// foreach (DataRow row in dt.Rows)
// {
// string i = row[0].ToString();
// string i1 = row[1].ToString();
// string i2 = row[2].ToString();
// string i3 = row[3].ToString();
// }
//}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
public partial class adduser : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand("insert into login values username = #un,password = #ps, sequirity_que = #sq, ans = #answer,usertype = #ustp ");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
cmd.Connection = con;
if (con.State != System.Data.ConnectionState.Open)
con.Open();
string un = txtusername.Text.Trim();
string ps = txtpass.Text.Trim();
string sq = txtseq.Text.Trim();
string answer = txtans.Text.Trim();
string ustp = DropDownList1.SelectedValue;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("un", un);
cmd.Parameters.AddWithValue("ps", ps);
cmd.Parameters.AddWithValue("sq", sq);
cmd.Parameters.AddWithValue("answer", answer);
cmd.Parameters.AddWithValue("ustp", ustp);
//string qry = "insert into login values (username = '" + txtusername.Text + "',password='" + txtpass.Text + "',sequirity_que='" + txtseq.Text + "',ans='" + txtans.Text + "',usertype='" + DropDownList1.SelectedValue + "') ";
//SqlCommand md = new SqlCommand(qry,con);
int n= cmd.ExecuteNonQuery();
if(n>0)
{
Response.Write("User added");
}
else
{
Response.Write("fail");
}
}
}
This is the correct syntax of INSERT INTO:
SqlCommand cmd = new SqlCommand("insert into login (username, password, sequirity_que, ans, usertype) values (#un, #ps, #sq, #answer, #ustp)");
Some good examples
I have a web form that uses a text box to update a comments field in the database. I would like to check for a blank before update and have a reminder box that says "Comment section blank, continue?", then have a yes / no option. This would allow the user to return to the update without making changes. The text box is visible when the user selects edit on the row in a gridview. I will provide code below so that anyone can see what I am doing. If this cannot be done this way, simply a message box saying that the comment section is blank would suffice.
Here is the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Configuration;
namespace AnnoTracker
{
public partial class WebForm1 : System.Web.UI.Page
{
public static class MyVariables
{
public static int PI = 0;
public static string JN = "";
public static string ST = "";
public static string AT = "";
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
dlAnnoType.SelectedValue = "Agency Error";
}
}
protected void EditSummary(object sender, GridViewEditEventArgs e)
{
gvSummary.EditIndex = e.NewEditIndex;
string _custName = gvSummary.DataKeys[e.NewEditIndex].Value.ToString();
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvSummary.EditIndex = -1;
BindData();
}
protected void gvSummary_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvSummary.PageIndex = e.NewPageIndex;
MyVariables.PI = e.NewPageIndex;
BindData();
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvSummary.EditIndex == e.Row.RowIndex)
{
DropDownList dlBU = (DropDownList)e.Row.FindControl("dlBU");
string _custName = gvSummary.DataKeys[e.Row.RowIndex].Values[1].ToString();
string BUquery = "select distinct Unit from vw_BU where Business='" + _custName + "'";
SqlCommand BUcmd = new SqlCommand(BUquery);
dlBU.DataSource = GetData(BUcmd);
dlBU.DataTextField = "Unit";
dlBU.DataValueField = "Unit";
dlBU.DataBind();
dlBU.Items.FindByValue((e.Row.FindControl("lblBU") as Label).Text).Selected = true;
DropDownList dlPA = (DropDownList)e.Row.FindControl("dlPA");
string _PAcustName = gvSummary.DataKeys[e.Row.RowIndex].Values[1].ToString();
string PAquery = "select PA from PA where Business='" + _PAcustName + "' order by PA";
SqlCommand PAcmd = new SqlCommand(PAquery);
dlPA.DataSource = GetData(PAcmd);
dlPA.DataTextField = "PA";
dlPA.DataValueField = "PA";
dlPA.DataBind();
dlPA.Items.FindByValue((e.Row.FindControl("lblPA") as Label).Text).Selected = true;
DropDownList dlET = (DropDownList)e.Row.FindControl("dlET");
string ETquery = "select distinct ErrorType from ErrorType order by ErrorType";
SqlCommand ETcmd = new SqlCommand(ETquery);
dlET.DataSource = GetData(ETcmd);
dlET.DataTextField = "ErrorType";
dlET.DataValueField = "ErrorType";
dlET.DataBind();
dlET.Items.FindByValue((e.Row.FindControl("lblET") as Label).Text).Selected = true;
DropDownList dlAA = (DropDownList)e.Row.FindControl("dlAA");
string AAquery = "select distinct AAA from ActualAgencyError";
SqlCommand AAcmd = new SqlCommand(AAquery);
dlAA.DataSource = GetData(AAcmd);
dlAA.DataTextField = "AAA";
dlAA.DataValueField = "AAA";
dlAA.DataBind();
dlAA.Items.FindByValue((e.Row.FindControl("lblAA") as Label).Text).Selected = true;
}
}
protected void UpdateSummary(object sender, GridViewUpdateEventArgs e)
{
string BU = (gvSummary.Rows[e.RowIndex].FindControl("dlBU") as DropDownList).SelectedItem.Value;
string ET = (gvSummary.Rows[e.RowIndex].FindControl("dlET") as DropDownList).SelectedItem.Value;
string AA = (gvSummary.Rows[e.RowIndex].FindControl("dlAA") as DropDownList).SelectedItem.Value;
string PA = (gvSummary.Rows[e.RowIndex].FindControl("dlPA") as DropDownList).SelectedValue;
string AnnotationNumber = gvSummary.DataKeys[e.RowIndex].Value.ToString();
string sgkComments = (gvSummary.Rows[e.RowIndex].FindControl("tbsgkComm") as TextBox).Text;
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
string query = "update vw_GridviewSource set [BusinessUnit] = #BU, [ErrorType] = #ET, [sgkComments] = #sgk, [ActualAgencyError] = #AA, [PA] = #PA where [AnnotationNumber] = #AnnoNum";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#BU", BU);
cmd.Parameters.AddWithValue("#AnnoNum", AnnotationNumber);
cmd.Parameters.AddWithValue("#ET", ET);
cmd.Parameters.AddWithValue("#AA", AA);
cmd.Parameters.AddWithValue("#sgk", sgkComments);
cmd.Parameters.AddWithValue("#PA", PA);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
//gvSummary.DataBind();
BindData();
}
private void BindData()
{
if (MyVariables.JN != "" && MyVariables.ST != "" && MyVariables.AT != "")
{
dlJobName.SelectedValue = MyVariables.JN;
dlJobName.DataBind();
dlStage.SelectedValue = MyVariables.ST;
dlStage.DataBind();
dlAnnoType.SelectedValue = MyVariables.AT;
dlAnnoType.DataBind();
}
String conString = System.Configuration.ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
string query = "select [Page_ID],[AnnotationNumber],[AnnotationBy],[PA],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust from vw_GridviewSource order by [Page_ID]";
SqlCommand cmd = new SqlCommand();
if (dlJobName.SelectedValue != "" & dlStage.SelectedValue != "")
{
query = "select [Page_ID],[AnnotationNumber],[AnnotationBy],[PA],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust from vw_GridviewSource where Name = '" + dlJobName.SelectedValue + "' and AnnotationDate = '" + dlStage.SelectedValue + "' order by [Page_ID]";
//cmd.Parameters.AddWithValue("#Name", dlJobName.SelectedValue);
//cmd.Parameters.AddWithValue("#Stage", dlStage.SelectedValue);
}
if (dlAnnoType.SelectedValue != "" && (dlJobName.SelectedValue != "" && dlStage.SelectedValue != ""))
{
query = "select [Page_ID],[AnnotationNumber],[AnnotationBy],[PA],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust from vw_GridviewSource where AnnotationType = '" + dlAnnoType.SelectedValue + "' and Name = '" + dlJobName.SelectedValue + "' and AnnotationDate = '" + dlStage.SelectedValue + "' order by [Page_ID]";
}
if (dlAnnoType.SelectedValue != "" && (dlJobName.SelectedValue.Length < 2 && dlStage.SelectedValue.Length < 2) )
{
query = "select [Page_ID],[AnnotationNumber],[AnnotationBy],[PA],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust from vw_GridviewSource where AnnotationType = '" + dlAnnoType.SelectedValue + "' order by [Page_ID]";
}
cmd.CommandText = query;
SqlConnection con = new SqlConnection(conString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
gvSummary.DataSource = ds;
gvSummary.PageIndex = MyVariables.PI;
gvSummary.DataBind();
//string #Name;
//string #Stage;
//#Name = dlJobName.SelectedValue;
//#Stage = dlStage.SelectedValue;
//string query = "select [AnnotationNumber],[AnnotationBy],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust from vw_GridviewSource where Name = '" + #Name + "' and AnnotationDate = '" + #Stage + "'";
//SqlCommand cmd = new SqlCommand(query);
//gvSummary.DataSource = GetData(cmd);
//gvSummary.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
protected void dlJobName_SelectedIndexChanged(object sender, EventArgs e)
{
MyVariables.JN = dlJobName.SelectedValue;
dlStage.DataBind();
MyVariables.ST = dlStage.SelectedValue;
gvSummary.DataBind();
BindData();
}
protected void dlStage_SelectedIndexChanged(object sender, EventArgs e)
{
MyVariables.JN = dlJobName.SelectedValue;
//dlStage.DataBind();
MyVariables.ST = dlStage.SelectedValue;
MyVariables.AT = dlAnnoType.SelectedValue;
gvSummary.DataBind();
BindData();
}
protected void dlAnnoType_SelectedIndexChanged(object sender, EventArgs e)
{
MyVariables.AT = dlAnnoType.SelectedValue;
MyVariables.JN = dlJobName.SelectedValue;
//dlStage.DataBind();
MyVariables.ST = dlStage.SelectedValue;
gvSummary.DataBind();
BindData();
}
}
}
You show only server side code, and it's more complicated doing chek on server side and show message on client.
Simple sample of chek on client side by javascript:
<script type="text/javascript">
function MyConfirm() {
if (document.getElementById("tb1").value == '')
if (confirm("Comment section blank, continue?"))
return true;
else
return false;
else true;
}
</script>
<asp:TextBox runat="server" ID="tb1" />
<asp:Button runat="server" ID="btn1" onclick="btn1_Click" OnClientClick="return MyConfirm();" Text="Save" />
i am trying to do sorting and paging for my gridview without datasource but when i click on the header of the gridview to sort it , nothing happen but when i click for paging is working fine and there is no error. how to do about it?
this is my code:
protected void Page_Load(object sender, EventArgs e)
{
dbBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dtSortTable = GridView1.DataSource as DataTable;
if (dtSortTable != null)
{
DataView dvSortedView = new DataView(dtSortTable);
dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection);
GridView1.DataSource = dvSortedView;
GridView1.DataBind();
}
}
private string getSortDirectionString(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
if(sortDirection== SortDirection.Ascending)
{
newSortDirection = "ASC";
}
else
{
newSortDirection = "DESC";
}
return newSortDirection;
}
private void dbBind()
{
DataSet ds;
string startdate = (string)(Session["startdate"]);
string enddate = (string)(Session["enddate"]);
var format = "dd/MM/yyyy";
DateTime one = DateTime.ParseExact(startdate, format, CultureInfo.InvariantCulture);
DateTime two = DateTime.ParseExact(enddate, format, CultureInfo.InvariantCulture);
if (two >= one)
{
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=n;Integrated Security=True");
//conn.Open();
SqlCommand cmd = new SqlCommand("SELECT [AmountSpent], [TimeDate]=convert(nvarchar,timedate,103), [StallNo] FROM [StudentTransactions] WHERE TimeDate BETWEEN #one AND #two", conn);
cmd.Parameters.AddWithValue("#one", one);
cmd.Parameters.AddWithValue("#two", two);
ds = new DataSet();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(ds);
if (ds.Tables.Count > 0)
{
DataView dv = ds.Tables[0].DefaultView;
if (ViewState["SortDirection"] != null)
{
sortDirection = ViewState["SortDirection"].ToString();
}
if (ViewState["SortExpression"] != null)
{
sortExpression = ViewState["SortExpression"].ToString();
dv.Sort = string.Concat(sortExpression, " ", sortDirection);
}
GridView1.DataSource = dv;
GridView1.DataBind();
}
}
//GridView1.DataBind();
//conn.Close();
}
else
{
GridView1.Visible = false;
string strMsg = " Data not found for the choosen dates.";
Response.Write("<script>alert('" + strMsg + "')</script>");
}
}
I have a method that reads data from a database table using SqlDataReader.
i assign data retrieved by SqlDataReader into a List and return it.
when i want to assign the List data from method into the List on Code behind file,
i encounter the following error:
and here is my code
public List<string> displayCustoemrhShipOrder()
{
List<string> drList = new List<string>();
int i = 0;
string sConnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
SqlConnection SqlCOn = new SqlConnection(sConnectionString);
SqlCommand SqlCmd = new SqlCommand();
SqlCmd.Connection = SqlCOn;
SqlCmd.CommandText = "displayCustomerShipOrder";
SqlCmd.CommandType = CommandType.StoredProcedure;
SqlCOn.Open();
SqlCmd.Parameters.AddWithValue("ShipOrderID",shipOrderID);
SqlDataReader reader = SqlCmd.ExecuteReader();
while (reader.Read())
{
drList.Insert(i, reader.GetValue(i).ToString());
i++;
}
//reader.Close();
//sqlCon.Close();
reader.Dispose();
SqlCOn.Dispose();
return (drList);
}
code behind code:
protected void Page_Load(object sender, EventArgs e)
{
// string shipOrderID = Session["shipOrderID"].ToString();
// int ID = Convert.ToInt32(shipOrderID);
int ID = 700;
Classes.CustomerShipOrder cuShipOrder = new Classes.CustomerShipOrder(ID);
List<string> ordrList = new List<string>(16);
ordrList= cuShipOrder.displayCustoemrhShipOrder();
cuid.Text = ordrList[0];
Label2.Text = ordrList[1];
Label3.Text = ordrList[2];
Label4.Text = ordrList[3];
Label5.Text = ordrList[4];
Label6.Text = ordrList[5];
Label7.Text = ordrList[6];
Label8.Text = ordrList[7];
Label9.Text = ordrList[8];
Label10.Text = ordrList[9];
Label11.Text = ordrList[10];
stored procedure used :
#ShipOrderID int
as
begin
select * from customerShipOrder where shipOrderID = #ShipOrderID;
end