GridView_RowUpdating method doesn't works in my asp.net project - c#

I have an asp.net project, in which columns in GridView adding manually by button click, here's the method:
protected void addVacations_Click(object sender, EventArgs e)
{
using (var conn = new NpgsqlConnection(connStr))
{
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("insert into vacations(id,name,date,nodes) values(DEFAULT, #imya, #data, #primVac)", conn);
cmd.Parameters.Add(new NpgsqlParameter("#imya", imya.Text));
cmd.Parameters.Add(new NpgsqlParameter("#data", data.Text));
cmd.Parameters.Add(new NpgsqlParameter("#primVac", primVac.Text));
cmd.ExecuteNonQuery();
Response.Redirect(Request.RawUrl);
}
}
I have two others buttons, that adding change GridView's columns by clicking them.
Now i have to add opportunity to change them online by clients. Here's the GridView code:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="id" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" Width="1650px" AutoGenerateDeleteButton="True" OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating" OnRowEditing="GridView1_RowEditing" AutoGenerateEditButton="True" >
Here's GridView1_RowUpdating method:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int ID5 = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string name = (row.FindControl("name") as TextBox).Text;
string date = (row.FindControl("date") as TextBox).Text;
string prim = (row.FindControl("nodes") as TextBox).Text;
string constr = ConfigurationManager.ConnectionStrings["postgresConnectionString"].ConnectionString;
using (NpgsqlConnection cn = new NpgsqlConnection(constr))
{
string query = "UPDATE vacations SET name=#name,date=#date,nodes=#prim Where id=#ID5";
NpgsqlCommand cmd = new NpgsqlCommand(query, cn);
cmd.Parameters.Add("#name", NpgsqlDbType.Varchar).Value = name;
cmd.Parameters.Add("#date", NpgsqlDbType.Varchar).Value = date;
cmd.Parameters.Add("#nodes", NpgsqlDbType.Varchar).Value = prim;
cmd.Parameters.Add("#id", NpgsqlDbType.Integer).Value = ID5;
cn.Open();
cmd.ExecuteNonQuery();
}
}
Right now i have next error when trying to change rows:
Server error in the application '/'.
The object reference does not point to an instance of the object.
Description: An unhandled exception occurred during the execution of the current web request. Examine the stack trace for more information about this error and the code snippet that caused it.
Exception Information: System.NullReferenceException: The object reference does not point to an instance of the object.
Source error:
Line 361: GridViewRow row = GridView1.Rows[e.RowIndex];
Line 362: int ID5 = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
Line 363: string name = (row.FindControl("name") as TextBox).Text;
The problem exactly in Line 363
I think the problem in my string, if be exact here:
string name = (row.FindControl("name") as TextBox).Text;
string date = (row.FindControl("date") as TextBox).Text;
string prim = (row.FindControl("nodes") as TextBox).Text;
So i need help how to correctly declare my strings? Or what wrong in my code.
Update. Here is my column details, all three buttons:
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.DataSource = null;//надо удалить текущие колонны (columns)
GridView1.DataBind();
for (int i = 0; GridView1.Columns.Count > i;)
{
GridView1.Columns.RemoveAt(i);
}
using (var conn = new NpgsqlConnection(connStr))
{
conn.Open();
bf1.HeaderText = "Направление деятельности";
bf1.DataField = "lineofbusiness";
bf1.ReadOnly = true;
bf1.SortExpression = "Napr";
bf2.HeaderText = "Объект";
bf2.DataField = "object";
bf2.SortExpression = "Obj";
bf3.HeaderText = "Мероприятия";
bf3.DataField = "events";
bf3.SortExpression = "Merop";
bf4.HeaderText = "Срок";
bf4.DataField = "deadline";
bf4.SortExpression = "Srok";
bf5.HeaderText = "Примечания";
bf5.DataField = "nodes";
bf5.SortExpression = "Prim";
GridView1.Columns.Add(bf1);
GridView1.Columns.Add(bf2);
GridView1.Columns.Add(bf3);
GridView1.Columns.Add(bf4);
GridView1.Columns.Add(bf5);
NpgsqlCommand cmd = new NpgsqlCommand();
NpgsqlDataAdapter sqlDa = new NpgsqlDataAdapter("SELECT id, lineofbusiness, object, events, deadline, nodes FROM mainpage where executor = '" + (string)Session["Name"] + "' ", conn);
//NpgsqlDataAdapter sqlDa1 = new NpgsqlDataAdapter("SELECT lineofbusiness, object, events, deadline, nodes FROM mainpage where executor = '" + curentExec + "' ", conn); //показ по исполнителю(раб код)
DataTable dtbl = new DataTable();
sqlDa.Fill(dtbl);
GridView1.DataSource = dtbl;
GridView1.DataBind();
Panel2.Visible = false;
Panel1.Visible = true;
Panel3.Visible = false;
//conn.Close(); //надо ли?
}
}
protected void Button2_Click(object sender, EventArgs e)
{
GridView1.DataSource = null;//надо удалить текущие колонны (columns)
GridView1.DataBind();
for (int i = 0; GridView1.Columns.Count > i;)
{
GridView1.Columns.RemoveAt(i);
}
using (var conn = new NpgsqlConnection(connStr))
{
conn.Open();
bf1.HeaderText = "Номер";
bf1.DataField = "id";
bf1.ReadOnly = true;
bf1.SortExpression = "11";
//bf2.HeaderText = "ФИО";
//bf2.DataField = "name";
//bf2.SortExpression = "22";
bf3.HeaderText = "Место";
bf3.DataField = "place";
bf3.SortExpression = "33";
bf4.HeaderText = "Цель";
bf4.DataField = "target";
bf4.SortExpression = "44";
bf5.HeaderText = "Срок";
bf5.DataField = "date";
bf5.SortExpression = "44";
bf6.HeaderText = "Результат";
bf6.DataField = "result";
bf6.SortExpression = "44";
GridView1.Columns.Add(bf1);
GridView1.Columns.Add(bf2);
GridView1.Columns.Add(bf3);
GridView1.Columns.Add(bf4);
GridView1.Columns.Add(bf5);
GridView1.Columns.Add(bf6);
NpgsqlCommand cmd = new NpgsqlCommand();
//NpgsqlDataAdapter sqlDavac = new NpgsqlDataAdapter("SELECT * FROM trips", conn);
NpgsqlDataAdapter sqlDavac = new NpgsqlDataAdapter("SELECT id, place, target, date, result FROM trips where name = '" + (string)Session["Name"] + "' ", conn);
DataTable dtblvac = new DataTable();
sqlDavac.Fill(dtblvac);
GridView1.DataSource = dtblvac;
GridView1.DataBind();
Panel1.Visible = false;
Panel2.Visible = false;
Panel3.Visible = true;
}
}
protected void Button3_Click(object sender, EventArgs e)
{
GridView1.DataSource = null;//надо удалить текущие колонны (columns)
GridView1.DataBind();
for (int i = 0; GridView1.Columns.Count > i;)
{
GridView1.Columns.RemoveAt(i);
}
using (var conn = new NpgsqlConnection(connStr))
{
conn.Open();
bf1.HeaderText = "Номер";
bf1.DataField = "id";
bf1.ReadOnly = true;
bf1.SortExpression = "NomerVac";
//bf2.HeaderText = "ФИО";
//bf2.DataField = "name";
//bf2.SortExpression = "NameVac";
bf3.HeaderText = "Дата";
bf3.DataField = "date";
bf3.SortExpression = "DataVac";
bf4.HeaderText = "Примечания";
bf4.DataField = "nodes";
bf4.SortExpression = "PrimVac";
GridView1.Columns.Add(bf1);
GridView1.Columns.Add(bf2);
GridView1.Columns.Add(bf3);
GridView1.Columns.Add(bf4);
NpgsqlCommand cmd = new NpgsqlCommand();
//NpgsqlDataAdapter sqlDavac = new NpgsqlDataAdapter("SELECT * FROM vacations", conn);
NpgsqlDataAdapter sqlDavac = new NpgsqlDataAdapter("SELECT id, date, nodes FROM vacations where name = '" + (string)Session["Name"] + "' ", conn);
DataTable dtblvac = new DataTable();
sqlDavac.Fill(dtblvac);
GridView1.DataSource = dtblvac;
GridView1.DataBind();
Panel1.Visible = false;
Panel2.Visible = true;
Panel3.Visible = false;
}
}

Related

sorting DGV on header click

Currently my system is connected via mysql data base to get the data from mysql to dgv.
I need a code that can blend with my current code on sorting the data when clicked on header. Sorry for poor english.
private void btnDisplay_Click(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString; //Set your MySQL connection string here.
string query = "SELECT lrn,first_name,middle_name,last_name,grade_and_section,student_gender,student_guardian,contact_number FROM student_info;"; // set query to fetch data "Select * from tabelname";
using (MySqlConnection conn = new MySqlConnection(connString))
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
dataStudent.DataSource = ds.Tables[0];
dataStudent.Columns[0].HeaderCell.Value = "LRN";
dataStudent.Columns[1].HeaderCell.Value = "First Name";
dataStudent.Columns[2].HeaderCell.Value = "Middle Name";
dataStudent.Columns[3].HeaderCell.Value = "Last Name";
dataStudent.Columns[4].HeaderCell.Value = "Grade And Section";
dataStudent.Columns[5].HeaderCell.Value = "Gender";
dataStudent.Columns[6].HeaderCell.Value = "Guardian";
dataStudent.Columns[7].HeaderCell.Value = "Contact Number";
dataStudent.Columns[5].Visible = false;
dataStudent.Columns[6].Visible = false;
dataStudent.Columns[7].Visible = false;
}
}
}
private void dataStudent_CellClick(object sender, DataGridViewCellEventArgs e)
{
int index = e.RowIndex;
DataGridViewRow selectedRow = dataStudent.Rows[index];
txtLRN.Text = selectedRow.Cells[0].Value.ToString();
txtFName.Text = selectedRow.Cells[1].Value.ToString();
txtMName.Text = selectedRow.Cells[2].Value.ToString();
txtLName.Text = selectedRow.Cells[3].Value.ToString();
txtYear.Text = selectedRow.Cells[4].Value.ToString();
txtGender.Text = selectedRow.Cells[5].Value.ToString();
txtGuardian.Text = selectedRow.Cells[6].Value.ToString();
txtContact.Text = selectedRow.Cells[7].Value.ToString();
}

Combobox empty and doesnt dropdown

I created a combobox column in a datagridview. The problem is my combobox is empty, blank, and doesn't dropdown when i click on it. When i use the debuger, every properties and value are ok and the items exists and are link to the combobox. Please help me :(
Code : `
public Repair()
{
Main pp = new Main();
InitializeComponent();
this.label4.Text = pp.label3.Text;
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE FComponent IS NOT NULL";
}
else
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
/**ArrayList list1 = new ArrayList(); //{ "C-C", "C-O", "Absence composant", "Mauvaise valeur", "Mauvais sens", "Mauvais composant" };
list1.Add("C-C");
list1.Add("C-O");**/
List<string> list1 = new List<string> { ("C-C"), ("C-O") };
combo.HeaderText = "FaultCodeByOp";
combo.DataPropertyName = "FaultCodeByOp";
combo.DropDownWidth = 120;
combo.FlatStyle = FlatStyle.Flat;
combo.Width = 90;
combo.DataSource = list1;
dataGridView1.Columns.AddRange(combo);
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToOrderColumns = true;
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for(int i=0;i<4;i++)
{
dataGridView1.Columns[i].ReadOnly = true;
}
}
foreach (DataGridViewRow row in dataGridView2.Rows)
{
for(int i=0;i<3;i++)
{
dataGridView2.Columns[i].ReadOnly = true;
}
}
}
/**private DataTable GetDescriptionTable()
{
DataTable l_dtDescription = new DataTable();
l_dtDescription.Columns.Add("FaultCodeByOp", typeof(string));
l_dtDescription.Rows.Add("C-O");
l_dtDescription.Rows.Add("C-C");
l_dtDescription.Rows.Add("Absence de composant");
l_dtDescription.Rows.Add("Mauvais composant");
l_dtDescription.Rows.Add("Mauvais sens");
l_dtDescription.Rows.Add("Mauvaise valeur");
return l_dtDescription;
}**/
private void textBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
string Var1 = textBox1.Text;
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailAndPass WHERE BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE SerialNum LIKE #SerialNum AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE SerialNum LIKE #SerialNum And FComponent IS NOT NULL";
}
}
else
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailOnly WHERE (BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent) AND ReportingOperator IS NULL ";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL ";
command1.CommandText = "SELECT DISTINCT Machine, BoardName, BoardNumber FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
}
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
}
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.IsCurrentRowDirty)
{
dataGridView1.Rows[e.RowIndex].Cells[6].Value = true;
}
}
private void metroButton1_Click(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((row.Cells[6].Value != null) && (bool)row.Cells[6].Value)
{
SqlCommand command = maConnexion.CreateCommand();
command = new SqlCommand("update FailAndPass set FaultCodeByOp=#Fault, RepairingDate=#RD, RepairingTime = #RT, ReportingOperator=#RO WHERE SerialNum=#Serial", maConnexion);
command.Parameters.AddWithValue("#Fault", row.Cells[4].Value != null ? row.Cells[4].Value : DBNull.Value);
command.Parameters.AddWithValue("#RD", DateTime.Today.ToString("d"));
command.Parameters.AddWithValue("#RT", row.Cells[5].Value != null ? row.Cells[5].Value : DBNull.Value);
command.Parameters.AddWithValue("#RO", this.label4.Text);
command.Parameters.AddWithValue("#Serial", this.textBox1.Text);
command.ExecuteNonQuery();
}
}
maConnexion.Close();
this.Hide();
Repair rep = new Repair();
rep.Show();
}
private void metroButton2_Click(object sender, EventArgs e)
{
this.Hide();
Main ff = new Main();
ff.Show();
}
/**private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex > -1)
{
// Bind grid cell with combobox and than bind combobox with datasource.
DataGridViewComboBoxCell l_objGridDropbox = new DataGridViewComboBoxCell();
// Check the column cell, in which it click.
if (dataGridView1.Columns[e.ColumnIndex].Name.Contains("FaultCodeByOp"))
{
// On click of datagridview cell, attched combobox with this click cell of datagridview
dataGridView1[e.ColumnIndex, e.RowIndex] = l_objGridDropbox;
l_objGridDropbox.DataSource = GetDescriptionTable(); // Bind combobox with datasource.
l_objGridDropbox.ValueMember = "FaultCodeByOp";
l_objGridDropbox.DisplayMember = "FaultCodeByOp";
}
}
}**/
}`
It seems that setting the DataGridViewComboBoxColumn to ReadOnly evokes this error in the loop:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i = 0; i < 4; i++)
{
dataGridView1.Columns[i].ReadOnly = true;
}
}
I am trying to find out why exactly..... for now avoid setting it to ReadOnly with a simple if clause:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i = 0; i < 4; i++)
{
if (!(dataGridView1.Columns[i] is DataGridViewComboBoxColumn))
{
dataGridView1.Columns[i].ReadOnly = true;
}
}
}
EDIT:
The Problem seems to be dataGridView1.Columns[0]. This column does not like it to be set with values or to be set to ReadOnly. It also seems not to have any name (tested it) which is very weird. Nontheless, if you start your loop at 1 the error will go away and you can have even your DataGridViewComboBoxColumn to be set to ReadOnly = true without the if clause:
for (int i = 1; i < 4; i++)
{
dataGridView1.Columns[i].ReadOnly = true;
}
Okay guys. I've done a new test.
Here is my test code :
combo.DataSource = list1;
if(combo.IsDataBound)
{
MessageBox.Show("TRUE");
}
else
{
MessageBox.Show("FALSE");
}
It seems that combo.datasource = list1 have all my value ("C-C" and "C-O"). But when i launch the debugger or launch the application, the messagebox which appear is the second one where combo.isdatabound = false. Normally, it should be True?

Procedure or function expects parameter which was not supplied - Parameter is in stored procedure(I think)

I've encountered an error which is absolutely driving me insane. Forgive me, I'm a novice, so I may be missing something out which is stupid or silly so sorry in advance.
I keep getting the error
"Procedure or function 'prcPersonalSelectedByPatientIdAppointmentSelect' expects parameter '#PatientNumber', which was not supplied."
This is baffling to me as '#PatientNumber' is in the stored procedure but my knowledge of SQL isn't the greatest.
ASPX Code
<asp:UpdatePanel ID="pnlUpdate" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlResults" runat="server" ScrollBars="Auto" >
<asp:GridView ID="gvAppointmentSearch" runat="server" Font-Names = "Arial"
Font-Size = "11pt" ForeColor = "#000000"
onselectedindexchanged="gvAppointmentSearch_SelectedIndexChanged"
AutoGenerateColumns = "false" DataKeyNames="PatientNumber" AllowPaging = "true"
OnPageIndexChanging = "OnPaging" PageSize = "10" Width = "100%"
HeaderStyle-BackColor = "#465c71" HeaderStyle-ForeColor = "#ffffff"
style="margin-bottom: 26px">
<Columns>
<%--Creates a select button that appear at the start of the grid view--%>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Select" ID="lnkSelect" runat="server" CommandName="Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Appointment Number" ItemStyle-Wrap="False">
<ItemTemplate>
<%--This will be the first field to appear beside the select button--%>
<asp:Label ID="lblAppointmentNumber" Text='<%# Eval("AppointmentNumber") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<%--Bound fields will place them in a specific order--%>
<asp:BoundField DataField = "AppointmentDate" HeaderText = "Appointment Date" DataFormatString="{0:d}" />
<asp:BoundField DataField = "AppointmentTime" HeaderText = "Appointment Time" DataFormatString="{0:d}" />
<asp:BoundField DataField = "Consultant" HeaderText="Referred By" ItemStyle-Wrap="False" />
<asp:BoundField DataField = "ByAttendance" HeaderText="Attendance"/>
</Columns>
</asp:GridView>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gvAppointmentSearch" />
</Triggers>
</asp:UpdatePanel>
C# Code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Populate dropdown if no record has been selected
String strConString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strConString);
conn.ConnectionString = strConString;
SqlCommand cmdInit = new SqlCommand();
cmdInit.CommandText = "Select * from DropdownCounty";
cmdInit.Connection = conn;
conn.Open();
DataTable dtInit = new DataTable();
dtInit.Load(cmdInit.ExecuteReader());
conn.Close();
dpdCounty.DataSource = dtInit;
dpdCounty.DataTextField = "County";
dpdCounty.DataValueField = "CountyID";
dpdCounty.DataBind();
DataSet ds = new DataSet();
ds = (DataSet)Session["DS"];
this.DataBindSearch();
try
{
//Fields that are required to be filled in if the information is avaliable
patientNumber.Text = ds.Tables[0].Rows[0]["PatientNumber"].ToString();
txtHCNumber.Text = ds.Tables[0].Rows[0]["HC_Number"].ToString();
//if (ds.Tables[0].Rows[0]["ConsentToDatabase"].ToString() != null)
//chkDBConsent.Checked = (bool)ds.Tables[0].Rows[0]["ConsentToDatabase"];
if (ds.Tables[0].Rows[0]["ConsentGivenDate"].ToString() != "dd/mm/yyyy")
{
if (ds.Tables[0].Rows[0]["ConsentGivenDate"].ToString() != null && ds.Tables[0].Rows[0]["ConsentGivenDate"].ToString() != "")
{
ConsentGivenDate.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["ConsentGivenDate"].ToString()).ToShortDateString();
}
}
IDnumberLegacy.Text = ds.Tables[0].Rows[0]["ID_Number_LegacyID"].ToString();
if (ds.Tables[0].Rows[0]["Sex"] != DBNull.Value)
{
//Datasource is added only when values are being added to allow for alterations to be made
//Allows for records with older dropdown values no longer selectable to be visible
String strConnString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.ConnectionString = strConnString;
SqlCommand cmd = new SqlCommand();
SqlCommand cmdPop = new SqlCommand();
cmd.CommandText = "Select Sex from DropdownSex";
cmd.Connection = con;
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
con.Close();
//String builder to gather records that are currently active
StringBuilder currentid = new StringBuilder();
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = dt.Rows[i];
currentid.AppendLine(string.Join(",", dr.ItemArray));
}
//convert stringbuilder to string
var output = currentid.ToString();
// Creates new StringReader instance from System.IO
using (StringReader reader = new StringReader(output))
{
// Loop over the lines in the string.
int count = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
count++;
if (line == (ds.Tables[0].Rows[0]["Sex"].ToString()))
cmdPop.CommandText = " Select * From DropdownSex";
}
}
if (cmdPop.CommandText == "")
cmdPop.CommandText = " Select * From DropdownSex";
cmdPop.Connection = con;
con.Open();
DataTable dtValues = new DataTable();
dtValues.Load(cmdPop.ExecuteReader());
con.Close();
dpdSex.DataSource = dtValues;
dpdSex.DataTextField = "Sex";
dpdSex.DataValueField = "SexID";
dpdSex.DataBind();
dpdSex.SelectedValue = ds.Tables[0].Rows[0]["SexID"].ToString();
}
txtPatientFirstName.Text = ds.Tables[0].Rows[0]["Forename"].ToString();
txtPatientSurname.Text = ds.Tables[0].Rows[0]["Surname"].ToString();
PatientMaiden.Text = ds.Tables[0].Rows[0]["MaidenName"].ToString();
if (ds.Tables[0].Rows[0]["DateOfBirth"].ToString() != "dd/mm/yyyy")
{
if (ds.Tables[0].Rows[0]["DateOfBirth"].ToString() != null && ds.Tables[0].Rows[0]["DateOfBirth"].ToString() != "")
{
txtDateOfBirth.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["DateOfBirth"].ToString()).ToShortDateString();
}
}
AddressLine1.Text = ds.Tables[0].Rows[0]["AddressLine1"].ToString();
AddressLine2.Text = ds.Tables[0].Rows[0]["AddressLine2"].ToString();
AddressLine3.Text = ds.Tables[0].Rows[0]["AddressLine3_TownCity"].ToString();
AddressLine4.Text = ds.Tables[0].Rows[0]["AddressLine4_Region"].ToString();
if (ds.Tables[0].Rows[0]["County"] != DBNull.Value)
{
//Datasource is added only when values are being added to allow for alterations to be made
//Allows for records with older dropdown values no longer selectable to be visible
String strConnString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.ConnectionString = strConnString;
SqlCommand cmd = new SqlCommand();
SqlCommand cmdPop = new SqlCommand();
cmd.CommandText = "Select County from DropdownCounty";
cmd.Connection = con;
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
con.Close();
//String builder to gather records that are currently active
StringBuilder currentid = new StringBuilder();
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = dt.Rows[i];
currentid.AppendLine(string.Join(",", dr.ItemArray));
}
//convert stringbuilder to string
var output = currentid.ToString();
// Creates new StringReader instance from System.IO
using (StringReader reader = new StringReader(output))
{
// Loop over the lines in the string.
int count = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
count++;
if (line == (ds.Tables[0].Rows[0]["County"].ToString()))
cmdPop.CommandText = " Select * From DropdownCounty";
}
}
if (cmdPop.CommandText == "")
cmdPop.CommandText = " Select * From DropdownCounty";
cmdPop.Connection = con;
con.Open();
DataTable dtValues = new DataTable();
dtValues.Load(cmdPop.ExecuteReader());
con.Close();
dpdCounty.DataSource = dtValues;
dpdCounty.DataTextField = "County";
dpdCounty.DataValueField = "CountyID";
dpdCounty.DataBind();
dpdCounty.SelectedValue = ds.Tables[0].Rows[0]["CountyID"].ToString();
}
PostCode.Text = ds.Tables[0].Rows[0]["PostCode"].ToString();
HomeTelNumber.Text = ds.Tables[0].Rows[0]["HomeTelNumber"].ToString();
MobileTelNumber.Text = ds.Tables[0].Rows[0]["MobileTelNumber"].ToString();
WorkTelNumber.Text = ds.Tables[0].Rows[0]["WorkTelNumber"].ToString();
PatientEmail.Text = ds.Tables[0].Rows[0]["Email"].ToString();
PatientNotes.Text = ds.Tables[0].Rows[0]["Notes"].ToString();
//Sets the color of the text box depedning if a value has been entered
string hex = "#F0F8FF";
if (txtDateOfBirth.Text != "dd/mm/yyyy")
txtDateOfBirth.ForeColor = System.Drawing.Color.Black;
else
txtDateOfBirth.BackColor = System.Drawing.ColorTranslator.FromHtml(hex);
if (ConsentGivenDate.Text != "dd/mm/yyyy")
ConsentGivenDate.ForeColor = System.Drawing.Color.Black;
else
ConsentGivenDate.BackColor = System.Drawing.ColorTranslator.FromHtml(hex);
}
//If the dataset is empty this is executed instead
catch (Exception fe)
{
lblErrors.Text = "New Record Successfully Started!";
//calls the poup to display a notification
dvMsg.Visible = true;
lblMsg.Text = "" + lblErrors.Text;
}
}
//Not required as this label has been replaced with a popup, still used to store message that will be displayed
lblErrors.Visible = true;
//Load the initial data from the session once
//***Custom error messages below***//
//Used to pull error message if someone else has already updated the data first
if (Session["ex"] != null)
{
var msg = Session["ex"].ToString();
//Message to be displayed
if (msg == "Error")
lblErrors.Text = "Update Failed! Someone has already made changes!";
else
lblErrors.Text = "Unable to update HC Number!";
//calls the popup to display a notification
dvMsg.Visible = true;
lblMsg.Text = "" + lblErrors.Text;
//required to prevent error message appearing everytime the page loads
Session["ex"] = null;
}
//As the page refreshes when a new record is added to allow the master page to display the new records details this is required to pull
//forward the success message to inform the user that the record has been added and the page has not just refreshed
if (Session["NewRecordAdded"] != null)
{
//Message to be displayed
lblErrors.Text = "Record Succesfully Added!";
//calls the popup to display a notification
dvMsg.Visible = true;
lblMsg.Text = "" + lblErrors.Text;
//required to prevent error message appearing everytime the page loads
Session["NewRecordAdded"] = null;
}
//Error when trying to find record that does not exist
if (Session["FindRecordError"] != null)
{
string a = Session["FindRecordError"].ToString();
//Message to be displayed
if (a == "Unable to locate")
lblErrors.Text = "Unable to find record!";
else
lblErrors.Text = "Full HC Number required!";
//calls the popup to display a notification
dvMsg.Visible = true;
lblMsg.Text = "" + lblErrors.Text;
//required to prevent error message appearing everytime the page loads
Session["FindRecordError"] = null;
}
if (Session["PersonalDeatilsSave"] != null)
{
//only if an update has occured
lblErrors.Text = "Save Successful!";
//calls the popup to display a notification
dvMsg.Visible = true;
lblMsg.Text = "" + lblErrors.Text;
//required to prevent error message appearing everytime the page loads
Session["PersonalDeatilsSave"] = null;
}
}
protected void gvAppointmentSearch_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
int index = gvAppointmentSearch.SelectedIndex;
string strConString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConString);
myConnect.ConnectionString = strConString;
string strCommandText = "prcPersonalSelectedByPatientIdAppointmentRetrieve";
try
{
SqlCommand sqlCmd = new SqlCommand(strCommandText, myConnect);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add(new SqlParameter("#PatientNumber", gvAppointmentSearch.DataKeys[index].Value.ToString()));
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlCmd;
da.Fill(ds, "personal");
//Needed to reset the clinical eval page for newly selected patient
Session["NDS"] = null;
}
catch (Exception fe)
{
lblMoreErrors.Text = "Error: " + fe.Message;
}
try
{
//Assigns the selected patients details to the dataset and redirects the user to the personal page
Session["DS"] = ds;
Response.Redirect("~/UserPages/PatientAppointment.aspx");
}
catch (Exception er)
{
lblErrors.Text = "Error: " + er.Message;
}
}
//Tells the gridview what to do when the page change is selected
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
this.DataBindSearch();
gvAppointmentSearch.PageIndex = e.NewPageIndex;
gvAppointmentSearch.DataBind();
}
protected void DataBindSearch()
{
DataSet ds = new DataSet();
string strConString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConString);
myConnect.ConnectionString = strConString;
string strCommandText = "prcPersonalSelectedByPatientIdAppointmentSelect";
try
{
SqlCommand sqlCmd = new SqlCommand(strCommandText, myConnect);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlCmd;
da.Fill(ds, "personal");
gvAppointmentSearch.DataSource = ds;
//Finally, all results matching the criteria will be placed into the gridview
gvAppointmentSearch.DataBind();
DataTable dt = new DataTable();
da.Fill(dt);
Session["CurrentData"] = dt;
//Counts the number of results found
lblResults.Text = "Results Found: " + ds.Tables.Cast<DataTable>().Sum(x => x.Rows.Count).ToString();
}
catch (Exception fe)
{
lblErrors.Text = "Error: " + fe.Message;
}
}
}
SQL Stored Procedure
ALTER PROCEDURE [dbo].[prcPersonalSelectedByPatientIdAppointmentSelect]
#PatientNumber int
AS
SELECT
[dbo].[Appointments].[AppointmentDate] as AppointmentDate
,dbo.Appointments.AppointmentTime as AppointmentTime
,[dbo].[DropdownReferredBy].[ReferredBy] as Consultant
,[dbo].[DropdownAttended].[ByAttendance] as ByAttendance
,dbo.Appointments.AppointmentNumber as AppointmentNumber
FROM [dbo].[PATIENTS]
LEFT JOIN dbo.Appointments on dbo.PATIENTS.PatientNumber = dbo.Appointments.PatientNumber
LEFT JOIN [dbo].[DropdownReferredBy] on dbo.Appointments.ReferredBy = [dbo].[DropdownReferredBy].ReferredBy
LEFT JOIN [dbo].[DropdownAttended] on dbo.Appointments.ByAttendance = dbo.DropdownAttended.ByAttendance
WHERE dbo.PATIENTS.PatientNumber LIKE #PatientNumber
ORDER BY AppointmentNumber ASC;
To add to all this, this page takes its data from another gridview with a connecting stored procedure.
Thanks in advance and sorry if I've done something very silly!!!
In your DataBindSearch() method, you are not providing a value for the #PatientNumber parameter. You need to specify that parameter and give it a value like you do further up in your code.
Also, while I have your attention, you should really be putting your SqlConnection and SqlCommand objects in using statements.
protected void DataBindSearch()
{
DataSet ds = new DataSet();
string strConString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
string strCommandText = "prcPersonalSelectedByPatientIdAppointmentSelect";
using (SqlConnection myConnect = new SqlConnection(strConString))
using (SqlCommand sqlCmd = new SqlCommand(strCommandText, connect))
{
try
{
SqlCommand sqlCmd = new SqlCommand(strCommandText, myConnect);
sqlCmd.CommandType = CommandType.StoredProcedure;
//You need to add the parameter before you call da.Fill()
sqlCmd.Parameters.Add(new SqlParameter("#PatientNumber", /*Parameter Value*/));
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlCmd;
da.Fill(ds, "personal");
gvAppointmentSearch.DataSource = ds;
//Finally, all results matching the criteria will be placed into the gridview
gvAppointmentSearch.DataBind();
DataTable dt = new DataTable();
da.Fill(dt);
Session["CurrentData"] = dt;
//Counts the number of results found
lblResults.Text = "Results Found: " + ds.Tables.Cast<DataTable>().Sum(x => x.Rows.Count).ToString();
}
catch (Exception fe)
{
lblErrors.Text = "Error: " + fe.Message;
}
}
}

How to get a new row from datatable for every click event for window from c#

i am having five rows in datatable i should get each row for every click event from datatable in windowform C# ?? I am using following code it works for only first row i.e getting only first record for every click event but i need each new row for every click event
private void Calculate_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
con.Open();
SqlCommand cmd3 = new SqlCommand("Select top " + que + " * from Samplebox", con);
SqlDataAdapter sdr = new SqlDataAdapter();
sdr.SelectCommand = cmd3;
sdr.Fill(ds, "Samplebox");
DataTable dt = new DataTable();
dt = ds.Tables["Samplebox"];
int i=+0;
if (i < ds.Tables[0].Rows.Count - 1 )
{
i++;
label3.Text = ds.Tables[0].Rows[i]["BoxIDPK"].ToString();
label4.Text = ds.Tables[0].Rows[i][Box Name""].ToString();
if (Convert.ToInt32(ds.Tables[0].Rows[i]["BoxType"]) == 0)
{
radioButton1.Visible = true;
radioButton2.Visible = true;
radioButton3.Visible = false;
radioButton4.Visible = false;
label7.Visible = false;
label8.Visible = false;
label5.Text = dt.Rows[i]["Option1"].ToString();
label6.Text = dt.Rows[i]["Option2"].ToString();
}
else if (Convert.ToInt32(ds.Tables[0].Rows[i]["BoxType"]) == 1)
{
radioButton1.Visible = true;
radioButton2.Visible = true;
radioButton3.Visible = true;
radioButton4.Visible = true;
}
}
con.Close();
}

Apply Column Filtering in Gridview in asp.net

I have a gridview which is populated at runtime with a table with unknow number of columns which are not known before hand.
I want to apply column filtering on all columns with Drop Down List.
How can I achieve it. Using Jquery, Linq or simple C sharp Coding.
public partial class DetailView : System.Web.UI.Page
{
public static int y = 0;
public static String colName = "";
public static Boolean flag = false;
static String folder = "";
static public MySqlConnection conn = null;
static public DropDownList dp = null;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
string strcon = ConfigurationManager.ConnectionStrings["abc"].ConnectionString;
conn = new MySqlConnection(strcon);
conn.Open();
Response.Write(Session["cols"].ToString());
Response.Write(Session["id"].ToString());
// Response.Write("qw");
folder = Session["folderName"].ToString();
colName = Session["cols"].ToString();
GridBind(folder, colName, flag);
}
protected void Page_Load(object sender, EventArgs e)
{
}
public void GridBind(String folder, String colName, Boolean val)
{
GridView1.DataSource = null;
GridView1.DataBind();
GridView1.Columns.Clear();
y = 0;
MySqlDataAdapter da;
if (val == false)
{
da = new MySqlDataAdapter("select * from " + folder + "", conn);
}
else
{
da = new MySqlDataAdapter("select * from " + folder + " where abc= '" + colName + "'", conn);
}
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataColumn coloumn in dt.Columns)
{
if (!coloumn.ColumnName.Equals("emp"))
{
var linkF = new TemplateField();
linkF.HeaderText = coloumn.ColumnName;
linkF.HeaderTemplate = new LinkColumn(ListItemType.Header, coloumn.ColumnName,folder);
linkF.ItemTemplate = new LinkColumn(ListItemType.Item, coloumn.ColumnName,folder);
GridView1.Columns.Add(linkF);
}
else if (coloumn.ColumnName.Equals("emp"))
{
//Response.Write("Came");
BoundField bfield = new BoundField();
////Initalize the DataField value.
bfield.DataField = coloumn.ColumnName;
////Initialize the HeaderText field value.
bfield.HeaderText = coloumn.ColumnName;
GridView1.Columns.Add(bfield);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
class LinkColumn : DetailView, ITemplate
{
int id;
ListItemType _item;
String colN = null;
String fold;
public LinkColumn(ListItemType item, String colNa, String f)
{
_item = item;
colN = colNa;
fold = f;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_item)
{
case ListItemType.Header:
DetailView.dp = new DropDownList();
Label lb = new Label();
MySqlCommand cm = new MySqlCommand("select distinct " + colN + " from " + fold + "", conn);
MySqlDataAdapter ad = new MySqlDataAdapter();
DataTable d = new DataTable();
ad.SelectCommand = cm;
ad.Fill(d);
DetailView.dp.DataTextField = colN;
DetailView.dp.DataValueField = colN;
DetailView.dp.DataSource = d;
DetailView.dp.DataBind();
lb.Text = colN.ToUpperInvariant();
dp.AutoPostBack = true;
dp.EnableViewState = true;
// DetailView.dp.ID = y.ToString();
y++;
container.Controls.Add(lb);
container.Controls.Add(DetailView.dp);
// DetailView.dp.ID = DetailView.y.ToString();
// Response.Write(_Default.dp.ID);
DetailView.dp.SelectedIndexChanged += new EventHandler(dp_Selected);
break;
case ListItemType.Item:
TextBox tb1 = new TextBox();
tb1.Enabled = false;
tb1.DataBinding += new EventHandler(tb1_Data);
tb1.Columns = 30;
container.Controls.Add(tb1);
break;
}
}
void tb1_Data(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
GridViewRow cont = (GridViewRow)txt.NamingContainer;
object dataV = DataBinder.Eval(cont.DataItem, colN);
if (dataV != DBNull.Value)
{
txt.Text = dataV.ToString();
}
}
void dp_Selected(object sender, EventArgs e)
{
DataTable a = new DataTable();
DropDownList list = (DropDownList)sender;
String name = list.SelectedValue;
// String ID = list.ID.ToString();
// Session["id"] = ID;
Session["cols"] = name;
DetailView.colName = Session["cols"].ToString();
DetailView.flag = true;
// Response.Write(DetailView.colName);
GridBind(fold, DetailView.colName, true);
}
}
}
When i am calling GridBind function from event handler it is giving Null pointer Excpetion at GridView1.DataSource = null;
My GridView1 is present in DetailView.aspx
}
Any help be highly appreciated
Thanks

Categories

Resources