no row at position 0 - c#

I have the following code snippet:
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
DataTable dt = ds.Tables["messages"];
DataRow dr = dt.Rows[0];
if (dt.Rows.Count > 0)
{
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}
}
But I'm getting an error as:
There is no row at position 0.
I have the same query in sql server, but my table has contents for this query.

You are not loading data in to the DataSet. You have to call SqlDataAdapter.Fill to load the data in the DataSet. Also assign the row in the condition where you check that Rows count is greater then zero for not getting exception when not row exists.
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
adap.Fill(ds);
DataTable dt = ds.Tables["messages"];
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}
}

Please check your updated code below
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
DataTable dt = ds.Tables["messages"];
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}

Related

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?

how to add button dynamically in gridview column?

i have this code of gridview. how do i enable button to be add inside all column in each row other than first column using this code ? i dont have templatefield or others assign for gridview because i declare gridview display through this code. how can i achieve that ? this is my code :
`protected void Page_Load(object sender, EventArgs e)
{
//where request_date >= DATEADD(day,-8, GETDATE())
con.Open();
DataTable dtTemp = new DataTable();
cmd = new SqlCommand("SELECT a.request_date,a.prod_line,a.jo_no,a.qty,CONVERT(VARCHAR(10),a.need_by_date ,101) as need_by_date,b.process_id FROM CutPanelCard a LEFT JOIN CutPanelConfirmation b on b.req_id=a.req_id where request_date >= DATEADD(day,-8, GETDATE()) order by request_date", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtTemp);
ViewState["Information"] = dtTemp;
try
{
{
//DataTable dtTemp = (DataTable)ViewState["Information"];
DataTable dtDistinctRecords = dtTemp.DefaultView.ToTable(true, "prod_line");
DataTable dtStudentName = dtTemp.DefaultView.ToTable(true, "request_date");
DataTable a = new DataTable();
DataTable dtStudent = new DataTable();
dtStudent.Columns.Add("request_date");
foreach (DataRow rows in dtDistinctRecords.Rows)
{
dtStudent.Columns.Add(rows["prod_line"].ToString());
}
foreach (DataRow row in dtStudentName.Rows)
{
DataRow dr = dtStudent.NewRow();
dr["request_date"] = row["request_date"];
DataView dv = new DataView(dtTemp);
dv.RowFilter = "request_date='" + row["request_date"] + "'";
DataTable dtStudentdtl = dv.ToTable();
for (int i = 0; i < dtStudentdtl.Rows.Count; i++)
{
string colValue = dtStudentdtl.Rows[i]["jo_no"].ToString();
string colValue2 = dtStudentdtl.Rows[i]["qty"].ToString();
string colValue3 = dtStudentdtl.Rows[i]["need_by_date"].ToString();
string colValue4 = dtStudentdtl.Rows[i]["process_id"].ToString();
dr[dtStudentdtl.Rows[i]["prod_line"].ToString()] = "JO: " + colValue + " Quantity: " + colValue2 + " Need by Date: " + colValue3 + " Completion Status: " + colValue4;
}
dtStudent.Rows.InsertAt(dr, dtStudent.Rows.Count);
}
GridView1.DataSource = dtStudent;
GridView1.DataBind();
GridView_Row_Merger(GridView1);
con.Close();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}`

ArgumentNullException while dealing with DataTable and DataAdapter in c#

i am using DataAdapter to fill my DataTable with query as Stored Procedure.
But there is an exception ArgumentNullExceptioncoming when i try to Fill DataTable. I tested the query and its working fine.
Here's my code:
if (!IsPostBack)
{
Session["NewsId"] = Convert.ToInt32(Request.QueryString["news"]);
if (Session["NewsId"] != null && Convert.ToInt32(Session["NewsId"]) != 0)
{
id = Convert.ToInt32(Session["NewsId"]);
}
}
da = new SqlDataAdapter("NewsGallerySelect", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("#NewsID", SqlDbType.Int).Value = id;
da.Fill(dt);
if (dt.Rows.Count > 0)
{
rptrNews.DataSource = dt;
rptrNews.DataBind();
foreach (DataRow row in dt.Rows)
{
lblShrtDesc.Text = row["ShortDesc"].ToString();
lblShrtDesc2.Text = row["ShortDesc"].ToString();
lblDesc.Text = row["NewsDesc"].ToString();
lblDesc2.Text = row["NewsDesc"].ToString();
lblDate.Text = row["NewsDate"].ToString();
}
}

Deleting multiple rows in datagridview using checkboxes-string was not recognized as a valid boolean

please help me I stuck in datagridview in c# winforms where my sql table looks like below
empcode-varchar(50)
fullname-varchar(50)
month-date
branch-varchar(50)
designation-varchar(50)
id-varchar(50)
accountno-nvarchar(50)
paymenttype-nvarchar(50)
basicsal-int
ca-int
hra-int
sa-int
totalsalary-int
allowanceid-int(IDENTITY COLUMN)
remark-nvarchar(50)
For this table i took two buttons one is viewdata and another is delete
my view data coding part working fine and is shown below:-
SqlDataAdapter da = new SqlDataAdapter("select * from allowance", cn);
dt = new System.Data.DataTable();
da.Fill(dt);
dg2.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dg2.Rows.Add();
dg2.Rows[n].Cells[0].Value = false;
dg2.Rows[n].Cells[1].Value = item["empcode"].ToString();
dg2.Rows[n].Cells[2].Value = item["fullname"].ToString();
dg2.Rows[n].Cells[3].Value = item["month"].ToString();
dg2.Rows[n].Cells[4].Value = item["branch"].ToString();
dg2.Rows[n].Cells[5].Value = item["designation"].ToString();
dg2.Rows[n].Cells[6].Value = item["id"].ToString();
dg2.Rows[n].Cells[7].Value = item["accountno"].ToString();
dg2.Rows[n].Cells[8].Value = item["paymenttype"].ToString();
dg2.Rows[n].Cells[9].Value = item["basicsal"].ToString();
dg2.Rows[n].Cells[10].Value = item["ca"].ToString();
dg2.Rows[n].Cells[11].Value = item["hra"].ToString();
dg2.Rows[n].Cells[12].Value = item["sa"].ToString();
dg2.Rows[n].Cells[13].Value = item["totalsalary"].ToString();
dg2.Rows[n].Cells[14].Value = item["allowanceid"].ToString();
dg2.Rows[n].Cells[15].Value = item["remark"].ToString();
}
and another button "delete" code is looks like this way:-
foreach (DataGridViewRow itemRow in dg2.Rows)
{
if (bool.Parse(itemRow.Cells[14].Value.ToString()))
{
da = new SqlDataAdapter("DELETE FROM allowance WHERE allowanceid = '" + itemRow.Cells[14].Value.ToString() + "'", cn);
DataTable bb = new DataTable();
da.Fill(bb);
}
}
MessageBox.Show("SuccessFully DELETED.....!");
foreach (DataGridViewRow itemRow in dg2.Rows)
{
if (!itemRow.IsNewRow)
{
if ((bool)itemRow.Cells[0].EditedFormattedValue)
{
da = new SqlDataAdapter("DELETE FROM allowance WHERE allowanceid = " + Convert.ToInt32(itemRow.Cells[14].Value) + "", cn);
DataTable bb = new DataTable();
da.Fill(bb);
try this
foreach (DataGridViewRow itemRow in dg2.Rows)
{
if (bool.Parse(Convert.Tostring(itemRow.Cells[14].Value)))
{
da = new SqlDataAdapter("DELETE FROM allowance WHERE allowanceid = '" + Convert.Tostring(itemRow.Cells[14].Value) + "'", cn);
DataTable bb = new DataTable();
da.Fill(bb);
}
}
MessageBox.Show("SuccessFully DELETED.....!");
wire this code in DaataError Event
private void DGData_DataError(object sender, DataGridViewDataErrorEventArgs anError)
{
if ((anError.Exception) is ConstraintException)
{
DataGridView grd1 = (DataGridView)sender;
grd1.Rows[anError.RowIndex].ErrorText = "an error";
grd1.Rows[anError.RowIndex].Cells[anError.ColumnIndex].ErrorText = "an error";
anError.ThrowException = false;
}
}
}

how to use repeater iteratively?

I have one repeater which displays the list of puja.i have also used one datalist to display the names of temples.whenever i click on search it displays only the last value of the repeater i.e it is taking only the last value of the repeater....my question is how to use loop inside a repeater???
here is my code behind how i used datalist and repeater:
protected void Page_Load(object sender, EventArgs e)
{
//lblnodatafound.Visible = true;
//lbldatafound.Visible = false;
if (Request.QueryString["search"] != null)
{
var dt = new DataTable("Data");
String source = Request.QueryString["search"];
var splitseparator = new string[] { " " };
String[] result = source.Split(splitseparator, StringSplitOptions.RemoveEmptyEntries);
foreach (String s in result)
{
if (IsAlphaNumeric(s) == true)
{
var dttemp = new DataTable();
dttemp = fnsearch(s);
dt.Merge(dttemp, true);
}
}
if (dt.Rows.Count != 0)
{
int count = dt.Rows.Count;
if (dt.Rows.Count > 0)
{
DataList1.DataSource = dt;
DataList1.DataBind();
lblnodatafound.Visible = false;
lbldatafound.Visible = true;
//added the repeater to display the list of puja
for (int i = 0; i < dt.Rows.Count; i++)
{
String id = dt.Rows[i]["id"].ToString();
string query = "select puja.id,puja.name as puja_name, mandir.name as mandir_name from puja,mandir where mandir.id= puja.with_mandir and puja.with_mandir = '" + id + "'";
conn.Open();
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataTable dt1 = new DataTable();
adp.Fill(dt1);
conn.Close();
if (dt1.Rows.Count > 0)
{
lblmandirpuja.Text = "Poja in " + dt1.Rows[0]["mandir_name"];
foreach (RepeaterItem repeatItem in Repeater1.Items){
Repeater1.DataSource = dt1;
Repeater1.DataBind();
}
}
}
}
}
else
{
lblnodatafound.Visible = true;
lbldatafound.Visible=false;
}
}
}
Try to change this line:
if (dt1.Rows.Count > 0)
for something like:
for(int i = 0; i < dt1.Rows.Count; i++)
And this one:
lblmandirpuja.Text = "Poja in " + dt1.Rows[0]["mandir_name"];
The 0 for the i:
lblmandirpuja.Text = "Poja in " + dt1.Rows[i]["mandir_name"];

Categories

Resources