how to retrieve sheet names into dropdownlist - asp.net

DataTable dtExcelSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
ArrayList aList = new ArrayList();
foreach (DataRow row in dtExcelSheetName.Rows)
{
aList.Add(row);
}
drpSeletSheet.DataSource = aList;
for (int i = 1; i < dtExcelRecords.Rows.Count + 1; i++)
{
drpSeletSheet.Items.Add(dtExcelRecords.Rows[i]["Table_Name"].ToString());
}
drpSeletSheet.DataBind();
objAdapter1.SelectCommand = cmd;
objAdapter1.Fill(dtExcelRecords);

Related

Unable to update the textbox values in the gridview[c# asp.net]

Getting old values in DataTable, I need new values which I updated. Please help me?
Update on button click
My code:
DataSet Ds = new DataSet();
string Query = "";
Query = "select Conv_0,Unit_0,Rate_0,Text_0,Barcode_0,Conv_1,Unit_1,Rate_1,Text_1,Barcode_1,Conv_2,Unit_2,Rate_2,Text_2,Barcode_2,Conv_3,Unit_3,Rate_3,Text_3,Barcode_3,Conv_4,Unit_4,Rate_4,Text_4,Barcode_4 from Prod_Unit where Code='" + a + "'";
Ds = SqlClass1.GetData_from_localhost(Query);
if (Ds.Tables[0].Rows.Count > 0)
{
dt.Columns.Clear();
dt.Rows.Clear();
dt.Columns.Add("NO");
dt.Columns.Add("UNITS");
dt.Columns.Add("CONVERSION");
dt.Columns.Add("BARCODE");
dt.Columns.Add("RATE 1");
dt.Columns.Add("RATE 2");
dt.Columns.Add("PRINT TEXT");
// dt.Rows.Add();
for (int i = 0; i < Ds.Tables[0].Columns.Count; i++)
{
if (i >= 0 && i <= 4)
{
dt.Rows.Add();
dt.Rows[i]["NO"] = i + 1;
string unit = Ds.Tables[0].Rows[0]["Unit_" + i + ""].ToString();
DataSet temp = SqlClass1.GetData_from_localhost("select Unit FROM Units where Code=" + unit + "");
if (temp.Tables[0].Rows.Count > 0)
{
dt.Rows[i]["UNITS"] = temp.Tables[0].Rows[0][0].ToString();
}
dt.Rows[i]["CONVERSION"] = Ds.Tables[0].Rows[0]["Conv_" + i + ""].ToString();
dt.Rows[i]["BARCODE"] = Ds.Tables[0].Rows[0]["Barcode_" + i + ""].ToString();
dt.Rows[i]["RATE 1"] = Ds.Tables[0].Rows[0]["Rate_" + i + ""].ToString();
dt.Rows[i]["RATE 2"] = Ds.Tables[0].Rows[0]["Rate_" + i + ""].ToString();
dt.Rows[i]["PRINT TEXT"] = Ds.Tables[0].Rows[0]["Text_" + i + ""].ToString();
}
}
if (i == 0)
{
// ViewState["CurrentTable"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
// SetPreviousData();
}
}
ViewState["CurrentTable"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
SetPreviousData();// function to get previous data in
textbox
This is my binding function that I call in postback. How can I get updated values in ViewState["CurrentTable"] = dt;
on Update Button
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("NO");
dt.Columns.Add("UNITS");
dt.Columns.Add("CONVERSION");
dt.Columns.Add("BARCODE");
dt.Columns.Add("RATE 1");
dt.Columns.Add("RATE 2");
dt.Columns.Add("PRINT TEXT");
dr = dt.NewRow();
dr["NO"] = 1;
dr["UNITS"] = string.Empty;
dr["CONVERSION"] = string.Empty;
dr["BARCODE"] = string.Empty;
dr["RATE 1"] = string.Empty;
dr["RATE 2"] = string.Empty;
dr["PRINT TEXT"] = string.Empty;
dt.Rows.Add(dr);
int rowIndex = 0;
for (int i = 0; i < GridView1.Rows.Count; i ++)
{
if (GridView1.Rows[rowIndex].RowType == DataControlRowType.DataRow)
{
DropDownList box1 = (DropDownList)GridView1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
TextBox box2 = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
TextBox box4 = (TextBox)GridView1.Rows[rowIndex].Cells[4].FindControl("TextBox4");
TextBox box5 = (TextBox)GridView1.Rows[rowIndex].Cells[5].FindControl("TextBox5");
TextBox box6 = (TextBox)GridView1.Rows[rowIndex].Cells[6].FindControl("TextBox6");
dt.Rows[i]["NO"] = i + 1;
dt.Rows[i]["Units"] = box1.Text;
dt.Rows[i]["Conversion"] = box2.Text;
dt.Rows[i]["Barcode"] = box3.Text;
dt.Rows[i]["Rate 1"] = box4.Text;
dt.Rows[i]["Rate 2"] = box5.Text;
dt.Rows[i]["Print Text"] = box6.Text;
dt.Rows.Add();
rowIndex++;
}
}
ViewState["CurrentTable"] = dt;
Save();//function for save
}

Find radio button control in nested repeater control in asp.net?

I have two repeater controls one inside other and in inner repeater there is placeholder in which radio button is dynamically generated. I want to find the radio button control to check whether it is checked or not? I want above all function to be performed in button submit/click event defined in the code?
if (!Page.IsPostBack)
{
//1) Load SomeDatatable from Database somehow
// Just for testing : replace with query to DB
strqry = "select * from Quiz_tblQsnsLimitMaster where Qsnexamname='" + Request.QueryString["QsnEname"].ToString() + "'";
SqlDataAdapter adp = new SqlDataAdapter(strqry, sCon);
DataSet ds = new DataSet();
try
{
adp.Fill(ds);
int total = ds.Tables[0].Rows.Count;
for (int i = 0; i < total; i++)
{
string QuesID = ds.Tables[0].Rows[i].ItemArray[1].ToString();
//SubName = ds.Tables[0].Rows[i].ItemArray[3].ToString();
DataSet oDs = SqlHelper.ExecuteDataset(sCon, "Ps_Quiz_OnlineTest_QuestionsWithOptions_Get", QuesID);
SomeDatatable.Merge(oDs.Tables[0]);
}
removeDuplicatesRows(SomeDatatable);
System.Data.DataColumn newColumn = new System.Data.DataColumn("ContentIndex", typeof(System.String));
newColumn.DefaultValue = "0";
SomeDatatable.Columns.Add(newColumn);
for (int i = 0; i < Math.Ceiling((decimal)SomeDatatable.Rows.Count); i++)
SomeDatatable.Rows[i]["ContentIndex"] = i + 1;
}
catch
{
}
////2) Create a dummy data source for the tab repeater using a list of anonymous types
List<object> TabList = new List<object>();
//BindSubject();
for (int I = 0; I < Math.Ceiling((decimal)SomeDatatable.Rows.Count / (decimal)ContentPerTab); I++)
{
TabList.Add(new { TabIndex = I });
}
TabRepeater.ItemDataBound += TabRepeater_ItemDataBound;
TabRepeater.DataSource = TabList;
TabRepeater.DataBind();
//TablLinkRepeater.DataSource = TabList;
//TablLinkRepeater.DataBind();
//}
}
public void removeDuplicatesRows(DataTable dt)
{
SomeDatatable = dt.DefaultView.ToTable(true, "QuestionId");
}
protected void TabRepeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
int TabIndex = -1;
int.TryParse(DataBinder.Eval(e.Item.DataItem, "TabIndex").ToString(), out TabIndex);
//Copy Content Rows from SomeDatable that belong to this tab
DataTable Dt = SomeDatatable.Clone();
for (Int32 i = TabIndex * ContentPerTab; i <= (TabIndex + 1) * ContentPerTab - 1; i++)
{
if (i >= SomeDatatable.Rows.Count) break;
Dt.ImportRow(SomeDatatable.Rows[i]);
}
// Find the content repeater in this item and use the new datatable as source
Repeater ContentRepeater = (Repeater)e.Item.FindControl("ContentRepeater");
ContentRepeater.ItemDataBound += ContentRepeater_ItemDataBound;
ContentRepeater.DataSource = Dt;
ContentRepeater.DataBind();
}
}
// This handler might be needed for content repeater, included just for testing
protected void ContentRepeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
//Read coulmn from Datarow
int ContentIndex = -1;
int.TryParse(DataBinder.Eval(e.Item.DataItem, "ContentIndex").ToString(), out ContentIndex);
var parsed = "'" + HttpUtility.ParseQueryString(DataBinder.Eval(e.Item.DataItem, "QuestionID").ToString()) + "'";
//Add Question
DataSet ds = SqlHelper.ExecuteDataset(sCon, "Ps_Quiz_QuestionsWithOptions_Get", Convert.ToString(parsed));
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
int iCnt = 0;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Table tblQsn = new Table();
//.....Begin Text Qsn Creation.....//
tblQsn.Width = new Unit("98%");
TableRow trQsn = new TableRow();
iRowCounter++;
trQsn.ID = "Row_" + iRowCounter.ToString();
TableCell tcQsn = new TableCell();
TableCell tcQsnSNo = new TableCell();
tcQsn.CssClass = "Label";
tcQsn.BackColor = System.Drawing.Color.Gainsboro;
tcQsn.Font.Bold = true;
tcQsn.Font.Size = 12;
tcQsn.Text = ds.Tables[0].Rows[i][1].ToString();
tcQsn.Width = Unit.Percentage(99.5);
iCellCounter++;
tcQsn.ID = "Cell_" + iCellCounter.ToString();
tcQsnSNo.CssClass = "Label";
tcQsnSNo.Attributes.Add("valign", "top");
tcQsnSNo.BackColor = System.Drawing.Color.Gainsboro;
tcQsnSNo.Font.Bold = true;
tcQsnSNo.Width = Unit.Percentage(0.5);
iCellCounter++;
tcQsnSNo.ID = "Cell_" + iCellCounter.ToString();
iCnt++;
tcQsnSNo.Text = ContentIndex.ToString() + ".";
trQsn.Cells.Add(tcQsnSNo);
trQsn.Cells.Add(tcQsn);
tblQsn.Rows.Add(trQsn);
int rcnt = i;
int iOptCnt = 0;
string sStatus = "N";
while ((rcnt >= 0) && (rcnt < ds.Tables[0].Rows.Count))
{
if (ds.Tables[0].Rows[rcnt][2].ToString() == ds.Tables[0].Rows[i][2].ToString())
{
if (sStatus == "N")
{
sStatus = "Y";
}
TableRow trQsnOpt = new TableRow();
iRowCounter++;
trQsnOpt.ID = "Row_" + iRowCounter.ToString();
TableCell tcQsnOpt = new TableCell();
tcQsnOpt.CssClass = "Label";
iCellCounter++;
tcQsnOpt.ID = "Cell_" + iCellCounter.ToString();
tcQsnOpt.Attributes.Add("valign", "top");
tcQsnOpt.VerticalAlign = VerticalAlign.Middle;
TableCell tcQsnOptSNo = new TableCell();
tcQsnOptSNo.CssClass = "Label";
iCellCounter++;
tcQsnOptSNo.ID = "Cell_" + iCellCounter.ToString();
iOptCnt++;
RadioButton oRbOptions = new RadioButton();
oRbOptions.GroupName = ds.Tables[0].Rows[rcnt][2].ToString() + "_Group";
oRbOptions.Text = ds.Tables[0].Rows[rcnt][3].ToString().Trim();
oRbOptions.Font.Size = 11;
iRbTCounter++;
oRbOptions.ID = ds.Tables[0].Rows[i][0].ToString() + "_" + ds.Tables[0].Rows[rcnt][2].ToString() + "_" + "Option" + iOptCnt.ToString() + "_" + iRbTCounter.ToString();
//oRbOptions.Enabled = false;
//if (ds.Tables[0].Rows[i][2].ToString() == "Option" + iRbTCounter.ToString())
//{
// oRbOptions.Checked = true;
//}
oRbOptions.InputAttributes.Add("data-info", Convert.ToString(ContentIndex));
oRbOptions.CssClass = "Label";
tcQsnOpt.Controls.Add(oRbOptions);
tcQsnOptSNo.Text = iOptCnt.ToString() + ".";
trQsnOpt.Cells.Add(tcQsnOptSNo);
trQsnOpt.Cells.Add(tcQsnOpt);
rcnt++;
//.....Add Option Image.....//
tblQsn.Rows.Add(trQsnOpt);
}
else
break;
}
i = rcnt - 1;
PlPreview = (PlaceHolder)e.Item.FindControl("PlPreview");
PlPreview.Controls.Add(tblQsn);
}
}
}
}
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
SubmitQuestion();
}
public void SubmitQuestion()
{
for (int c = 0; c < SomeDatatable.Rows.Count; c++)
{
string sQsnOptId = SomeDatatable.Rows[c]["QuestionID"].ToString();
DataSet ds = SqlHelper.ExecuteDataset(sCon, "Ps_Quiz_QuestionsWithOptions_Get", "'" + sQsnOptId + "'");
for (int i = 1; i <= 4; i++)
{
string rdboption = ds.Tables[0].Rows[c][0].ToString() + "_" + ds.Tables[0].Rows[i-1][2].ToString() + "_" + "Option" + i + "_" + i;
Repeater rpt = (Repeater)TabRepeater.NamingContainer.FindControl("ContentRepeater");
RadioButton rbt = (RadioButton)rpt.NamingContainer.FindControl(rdboption);
if (rbt.Checked)
{
strqry = "update Quiz_tblOnlineTest_Detail set UserAns='Option" + i + "', DeletionStatus='A' where CreationLogInId='AMITSAMBYAL#HOTMAIL.COM' and ExamName='" + Request.QueryString["QsnEname"].ToString() + "' and QsnId=" + Session["quesid"].ToString() + "";
cmd = new SqlCommand(strqry, con);
try
{
cmd.ExecuteNonQuery();
}
catch
{
}
finally
{
con.Close();
}
break;
}
}
}
}
}
I found the answer. Thanks
foreach (RepeaterItem repeater in TabRepeater.Items)
{
Repeater repeater1 = (Repeater)repeater.FindControl("ContentRepeater");
foreach (RepeaterItem repItem in repeater1.Items)
{
for (int i = 1; i <= 4; i++)
{
string rdboption = ds.Tables[0].Rows[c][0].ToString() + "_" + ds.Tables[0].Rows[i - 1][2].ToString() + "_" + "Option" + i + "_" + i;
PlaceHolder PlPreview = (PlaceHolder)repItem.FindControl("PlPreview");
rbt = (RadioButton)PlPreview.FindControl(rdboption);
if (rbt.Checked)
{
// statement
}
}
}
}
}
}

Exception Occurs While Opening a Downloaded Excel Sheet(.xls) In Asp.Net

I download an Excel Sheet by using the following code.
The above code is starting code of my logic.After downloaded, I open the Excel Sheet.It shows an Warning like this
Because of this warning,when Im trying to upload the same page to Mysql DataBase using Asp.Net.It shows an Exception like "Page is not in correct Format".
This Is My Entire Logic For Downloading an Excel Sheet
protected void download_Click(object sender, EventArgs e)
{
ExportToExcel(SqlDataSource1, "StudentMarks");
}
public void ExportToExcel(SqlDataSource dataSrc, string fileName)
{
//Add Response header
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";
Response.ContentType = "application/ms-excel";
//GET Data From Database
MySqlConnection cn = new MySqlConnection(dataSrc.ConnectionString);
// string query = dataSrc.SelectCommand.Replace("\r\n", " ").Replace("\t", " ");
MySqlCommand cmd9 = new MySqlCommand("select subject from class_subject where standard='" + DropDownList1.SelectedItem.Value + "';", cn);
// cn.Open();
//DataSet ds9=new DataSet();
MySqlDataAdapter da9 = new MySqlDataAdapter(cmd9);
// da9.Fill(ds9);
DataTable dt = new DataTable();
da9.Fill(dt);
StringBuilder sb9 = new StringBuilder();
for (int count = 0; count < dt.Rows.Count; count++)
{
// string headerRowText = GridView4.HeaderRow.Cells[i].Text;
sb9.Append("'");
sb9.Append(dt.Rows[count][0].ToString());
sb9.Append("'");
if (count < dt.Rows.Count - 1)
//if (count < count3 - 1)
{
sb9.Append(",");
}
}
Label2.Text = sb9.ToString();
//MySqlCommand fyearcmd = new MySqlCommand("select fyear from student_data where standard='" + DropDownList1.SelectedItem.Value + "' and completed_status='running';", cn);
//MySqlDataReader fyeardr = fyearcmd.ExecuteReader();
string query = "select Admission_Num,Name,'Standard','Fyear','Type_of_exam'," + sb9.ToString() + " from student_data where standard='" + DropDownList1.SelectedItem.Value + "' and fyear='" + DropDownList4.SelectedItem.Value + "';";
MySqlCommand cmd = new MySqlCommand(query, cn);
cmd.CommandTimeout = 999999;
cmd.CommandType = CommandType.Text;
try
{
cn.Open();
MySqlDataReader dr = cmd.ExecuteReader();
StringBuilder sb = new StringBuilder();
//Session["fieldcount"] = dr.FieldCount.ToString();
//Label1.Text = dr.FieldCount.ToString();
//Add Header
int count3 = 4;
for (int count = 0; count < dr.FieldCount; count++)
//for (int count = 0; count < count3; count++)
{
if (dr.GetName(count) != null)
sb.Append(dr.GetName(count));
if (count < dr.FieldCount - 1)
//if (count < count3 - 1)
{
sb.Append("\t");
}
}
Response.Write(sb.ToString() + "\n");
Response.Flush();
//Append Data
while (dr.Read())
{
sb = new StringBuilder();
//for (int col = 0; col < dr.FieldCount - 1; col++)
for (int col = 0; col <= count3; col++)
{
if (col < (count3 - 2))
{
if (!dr.IsDBNull(col))
sb.Append(dr.GetValue(col).ToString().Replace(",", " "));
sb.Append("\t");
}
if (col == (count3 - 2))
{
if (!dr.IsDBNull(col))
sb.Append(DropDownList1.SelectedItem.Text);
sb.Append("\t");
}
if (col == (count3 - 1))
{
if (!dr.IsDBNull(col))
{
//sb.Append(dr.GetValue(col).ToString().Replace(",", " "));
sb.Append(DropDownList4.SelectedItem.Text);
}
sb.Append("\t");
}
if (col == count3)
{
if (!dr.IsDBNull(col))
{
//sb.Append(dr.GetValue(col).ToString().Replace(",", " "));
sb.Append(DropDownList3.SelectedItem.Text);
}
sb.Append("\t");
}
}
//if (!dr.IsDBNull(dr.FieldCount - 1))
// sb.Append(dr.GetValue(dr.FieldCount - 1).ToString().Replace(",", " "));
Response.Write(sb.ToString() + "\n");
Response.Flush();
}
dr.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
cmd.Connection.Close();
cn.Close();
}
Response.End();
}
So Please give me the suggestion how to download the Excel Sheet with out showing errors while opening.
You you are generating a csv file, not a excel file. Try to change you header:
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");
Normally excel is default for opening csv files.

Label does not show up in asp.net

I have a label in asp.net page and change its text in certain situations. Here is the code:
<asp:Label ID="errorMessage" runat="server" Text="Label" Visible="False"></asp:Label>
errorMessage.Text = MyGlobals.student.registerCourse(c, ref addList, course).ToString();
errorMessage.ForeColor = System.Drawing.Color.Red;
errorMessage.Visible = true;
When i debugged, i saw that MyGlobals.student.registerCourse(c, ref addList, course).ToString() method returns my error message well. Then i set the label visible, but when page loads i cannot see the label. Also, while debugging i saw that "textsetbyaddparsedsubobject" property of the label is false. Can that be the problem? Why is not the label being showed in my page? Can anyone help?
Thanks.
Edit: Here is the full code:
protected void bSubmitChanges_Click1(object sender, EventArgs e)
{
Userfunctions function = new Userfunctions();
List<string> dropList = new List<string>();
List<string> addList = new List<string>();
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
SqlCommand cmd;
con.Open();
string ID = MyGlobals.currentID;
try
{
for (int i = 1; i <= 6; i++)
{
string course;
if ((course = boxCRN(i)) != "")
{
cmd = new SqlCommand("select count (*) from CourseTable where CRN=#course", con);
cmd.Parameters.AddWithValue("#course", course);
int result = Convert.ToInt32(cmd.ExecuteScalar());
if (result > 0)
{
cmd = new SqlCommand("select * from CourseTable where CRN=#course", con);
cmd.Parameters.AddWithValue("#course", course);
cmd.ExecuteScalar();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
string query = "SELECT * FROM CourseTable WHERE CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'";
cmd = new SqlCommand(query, con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0];
cmd = new SqlCommand("select * from PrereqTable where CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'", con);
da2 = new SqlDataAdapter(cmd);
dt2 = new DataTable();
da2.Fill(dt2);
List<string> pre = new List<string>();
foreach (DataRow dr5 in dt2.Rows)
{
pre.Add(Convert.ToString(dr5["pCourseCode"]) + Convert.ToString(dr5["pCourseNumber"]));
}
Course c = new Course(dr2["InstructorID"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
c.addPrereq(pre);
string message = MyGlobals.student.registerCourse(c, ref addList, course).ToString();
errorMessage.Text = message;
errorMessage.ForeColor = System.Drawing.Color.Red;
errorMessage.Visible = true;
Label1.Visible = true;
Label1.Text = "asdasdasd";
}
}
}
}
}
catch (Exception) { }
for (int i = 0; i < showCourses.Rows.Count; i++)
{
string a = ((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue;
if (((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue == "1")
{
string courseCode = showCourses.Rows[i].Cells[1].Text, courseNumber = showCourses.Rows[i].Cells[2].Text;
SqlCommand com = new SqlCommand("select * from CourseTable where CourseCode=#courseCode and CourseNumber=#courseNumber", con);
com.Parameters.AddWithValue("courseCode", courseCode);
com.Parameters.AddWithValue("courseNumber", courseNumber);
try
{
SqlDataAdapter da2 = new SqlDataAdapter(com);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0];
Course c = new Course(dr2["InstructorID"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
Register reg = new Register(c, MyGlobals.student);
MyGlobals.student.dropCourse(reg);
dropList.Add(showCourses.Rows[i].Cells[1].Text + showCourses.Rows[i].Cells[2].Text);
}
catch (Exception) { }
}
}
foreach (string course in dropList)
{
for (int i = 0; i < MyGlobals.student.getRegistered().Count; i++ )
{
if (MyGlobals.student.getRegistered()[i].getCourse().getCode().ToString() + MyGlobals.student.getRegistered()[i].getCourse().getNumber().ToString() == course)
MyGlobals.student.dropCourse(MyGlobals.student.getRegistered()[i]);
}
cmd = new SqlCommand("delete from RegisterTable where StudentID='" + MyGlobals.currentID + "' and CourseCode='" + course.Substring(0, course.Length - 3) + "' and CourseNumber='" + course.Substring(course.Length - 3, 3) + "'", con);
cmd.ExecuteNonQuery();
}
try
{
foreach (string courses in addList)
{
string courseCode = "";
string courseNumber = "";
string term = MyGlobals.currentTerm + " " + MyGlobals.currentYear;
string q = ("select CourseCode from CourseTable where CRN=#courses");
string grade = "";
SqlCommand command = new SqlCommand(q, con);
command.Parameters.AddWithValue("#courses", courses);
courseCode = Convert.ToString(command.ExecuteScalar());
q = ("select CourseNumber from CourseTable where CRN=#courses");
command = new SqlCommand(q, con);
command.Parameters.AddWithValue("#courses", courses);
courseNumber = Convert.ToString(command.ExecuteScalar());
cmd = new SqlCommand("insert into RegisterTable (CourseCode,CourseNumber,Term,StudentID,Grade) values(#courseCode,#courseNumber,#term, #ID,'U')", con);
cmd.Parameters.AddWithValue("#courseCode", courseCode);
cmd.Parameters.AddWithValue("#courseNumber", courseNumber);
cmd.Parameters.AddWithValue("#term", term);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
}
}
catch (Exception) { }
con.Close();
Response.Redirect("AddDropClasses.aspx");
}
}
And the registerCourse function:
public string registerCourse(Course course, ref List <string> addList, string crn) {
bool registered = true;
string message ="";
foreach (string s in course.getTime())
{
Userfunctions f = new Userfunctions();
foreach (Register r in this.register) {
if (r.getCourse().getTerm() == MyGlobals.currentTerm.ToString() + " " + MyGlobals.currentYear.ToString() && !f.TimeCheck(s, r.getCourse().getTime()))
{
registered = false;
message = "Time conflict";
}
}
}
if (registered) {
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string id = MyGlobals.currentID;
SqlCommand cmd = new SqlCommand("SELECT count (*) from RegisterTable where CourseCode ='" + course.getCode() +"' and CourseNumber='" + course.getNumber() + "' and Term='" + course.getTerm()+"'" , con);
cmd.Parameters.AddWithValue("#id", id);
int active = Convert.ToInt32(cmd.ExecuteScalar());
if (active >= Convert.ToInt32(course.getCapacity())){
registered = false;
message = "Not enough capacity";
}
if (registered) {
foreach (string s in course.getPrerequisites()) {
if (!hasPassedCourse(s)) {
registered = false;
message = "Prerequisite error";
}
}
}
}
if (registered)
{
Register reg = new Register(course, MyGlobals.student);
MyGlobals.student.addToSchedule(reg);
addList.Add(crn);
}
return message;
}
Remove below line
Response.Redirect("AddDropClasses.aspx");
it will load your page again as new page
When you have Visible="false" set on the control then the control properties may not been instatiated fully.
I would try hiding the control using, errorMessage.Visible=false in the code-behind in your Page_Load instead.

Update one cell after adding the new row with same values in gridview

I want to make shopping cart Datatable, I wrote the following code here to make the list of products
public DataTable ShoppingCartlist(string proname , string country,
string area ,string address,int quantity,decimal price,DateTime date)
{
DataTable dt = new DataTable();
if (HttpContext.Current.Session["ShoppingList"]==null)
{
dt.Columns.Add("ProName");
dt.Columns.Add("odate");
dt.Columns.Add("ocountry");
dt.Columns.Add("oarea");
dt.Columns.Add("oaddress");
dt.Columns.Add("quantity");
dt.Columns.Add("price");
dt.Columns.Add("SubTotal");
dt.Constraints.Add("Proid_PK", dt.Columns[0], true);
}
else
{
dt = (DataTable)HttpContext.Current.Session["ShoppingList"];
DataRow dr = dt.NewRow();
dr[0] = proname;
dr[1] = date;
dr[2] = country;
dr[3] = area;
dr[4] = address;
dr[5] = quantity;
dr[6] = price;
dr[7] = quantity * price;
dt.Rows.Add(dr);
}
return dt;
}
It binds the data fine with no problem, but where I insert the same row with same value it inserted in new record in the gridview, I don't want it like that I want update just one cell (I mean when I add new record with same values I want Quantity value on increase without adding new record in gridview) like I mark on the image
after long testing and googleing i finally get it done , here the code i used
public DataTable ShoppingCartlist(string proname , string country,
string area ,string address,int quantity,decimal price,DateTime date)
{
DataTable dt = new DataTable();
if (HttpContext.Current.Session["ShoppingList"]==null)
{
dt.Columns.Add("ProName");
dt.Columns.Add("odate");
dt.Columns.Add("ocountry");
dt.Columns.Add("oarea");
dt.Columns.Add("oaddress");
dt.Columns.Add("quantity");
dt.Columns.Add("price");
dt.Columns.Add("SubTotal");
DataRow dr = dt.NewRow();
dr[0] = proname;
dr[1] = date;
dr[2] = country;
dr[3] = area;
dr[4] = address;
dr[5] = quantity;
dr[6] = price;
dr[7] = quantity * price;
dt.Rows.Add(dr);
}
else
{
dt = (DataTable)HttpContext.Current.Session["ShoppingList"];
DataView dv = dt.DefaultView;
dv.Sort = "ProName";
int found;
string Proname;
DataRow dr;
for (int i = 0; i < dt.Rows.Count; i++)
{
dr = dt.Rows[i];
Proname = dr[0].ToString();
found = dv.Find(Proname);
if (found != -1)
{
foreach (DataRow pro in dt.Rows)
{
for (int x = 0; x < dt.Rows.Count; x++)
{
if (dt.Rows[x]["ProName"].ToString()==Proname)
{
dt.Rows[x]["quantity"] = Convert.ToInt16(dt.Rows[x]["quantity"]) + quantity;
}
}
}
}
}
}
return dt;
}
You could use LINQ:
DataTable dt = new DataTable("products");
dt.Columns.Add("ProName", typeof(string));
dt.Columns.Add("odate", typeof(DateTime));
dt.Columns.Add("ocountry", typeof(string));
dt.Columns.Add("oarea", typeof(string));
dt.Columns.Add("oaddress", typeof(string));
dt.Columns.Add("quantity", typeof(int));
dt.Columns.Add("price", typeof(decimal));
dt.Columns.Add("SubTotal", typeof(decimal));
DataRow dr1 = dt.NewRow();
dr1[0] = "test";
dr1[1] = new DateTime(2005, 5, 15);
dr1[2] = "US";
dr1[3] = "test area";
dr1[4] = "555";
dr1[5] = 1;
dr1[6] = 5.25;
dr1[7] = 5.25 * 1;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2[0] = "test";
dr2[1] = new DateTime(2005, 5, 15);
dr2[2] = "US";
dr2[3] = "test area";
dr2[4] = "555";
dr2[5] = 3;
dr2[6] = 5.25;
dr2[7] = 5.25 * 3;
dt.Rows.Add(dr2);
var shoppingCart = from r in dt.AsEnumerable()
group r by new
{
ProName = r.Field<string>("ProName"),
odate = r.Field<DateTime>("odate"),
ocountry = r.Field<string>("ocountry"),
oarea = r.Field<string>("oarea"),
oaddress = r.Field<string>("oaddress"),
price = r.Field<decimal>("price")
} into g
select new
{
g.Key.ProName,
g.Key.odate,
g.Key.ocountry,
g.Key.oarea,
g.Key.oaddress,
g.Key.price,
quantity = g.Sum(s1 => s1.Field<int>("quantity")),
SubTotal = g.Sum(s2 => s2.Field<decimal>("SubTotal"))
};
foreach (var p in shoppingCart)
{
Console.WriteLine("Product: {0}, Quantity: {1}, Subtotal: {2}", p.ProName, p.quantity, p.SubTotal);
}
Results:
Product: test, Quantity: 4, Subtotal: 21.00

Resources