الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

كيف أضيف خيار ( Delete ) لل Gridview برمجياً !

مغلق
بدأه يوفي VIP في 10 ديسمبر 2007 · 9 رد · 1,763 مشاهدة · في ASP.NET
مشاركة: واتساب X فيسبوك تيليجرام
#1 صاحب الموضوع

السلام عليكم ورحمة الله ..

كيف حالكم اخواني الكرام ان شاء الله بخير ...

سؤالي بسيط ان شاء الله اخواني الكرام ..

اضفت GridView وقمت بعمل الربط من خلال كود برمجي ..

أريد ان اضيف خيار الحذف ( Delete ) برمجياً يا أخوان ...

انا عرفت اضيف كلمة Delete ولكن لا اعرف كيف اكتب بداخله أي امر ّ!!

وفقكم الله لكل خير ..

#2
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:hayatConnectionString %>" SelectCommand="SELECT * FROM [department] order by [pid]" DeleteCommand="DELETE FROM [department]WHERE [ID] = @id">
   <DeleteParameters>
				<asp:Parameter Name="id" />
			</DeleteParameters>

			<UpdateParameters>
			<asp:Parameter name="pid"/>
			<asp:Parameter name="id"/>
			</UpdateParameters>

</asp:SqlDataSource>

هذا كود الاتصال لاحظ كيف عرقنا الأمر والمتغيرات فيه

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="id" DataSourceID="SqlDataSource1">
	<Columns>
		<asp:CommandField ShowDeleteButton="True" HeaderText="delete"/>
		<asp:BoundField ReadOnly="True" Visible="false" HeaderText="ID" InsertVisible="False" DataField="ID" SortExpression="ID" />
		 <asp:BoundField  HeaderText="pID" DataField="pID" SortExpression="pID" />
		<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
	</Columns>
</asp:GridView>

وهنا الجريد فيو

هذه الطريقه اللتي اتبعها ما ادري اذا في احد عنده طريقه افضل

وتمنى لك الفائده

تم تعديل هذه المشاركة بواسطة السـاحر في 10 ديسمبر 2007 في 17:22

joseph.gif

logo.gif

CCNA 640-802

مدونتي

#3

بارك الله فيك يالغالي ..

انا حاولت من قبل أن اجرب هذا الكود .. ولكن توقفت بصراحة عند SqlDataSource1 :(

مثل ما قلت انا استخدمت الربط البرمجي بالأكواد دون استخدام اي اداة للربط !:(

فمالعمل !!

#4
يوفي VIP كتب:
بارك الله فيك يالغالي ..

انا حاولت من قبل أن اجرب هذا الكود .. ولكن توقفت بصراحة عند SqlDataSource1 :(

مثل ما قلت انا استخدمت الربط البرمجي بالأكواد دون استخدام اي اداة للربط !:(

فمالعمل !!

يا اخي الكريم هل ممكن ان تشرح لنا كيف تقوم بعملية جلب البيانات من الـdatabase حتى نستطيع مساعدتك

-----------------------------------------------------------------------------------------------------------------------------





 

ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــ

Mohammad Sonaiea
 

#5

جزاك الله كل الخير استاذي محمد بارك الله فيك ..

انا عملت Class بالشكل التالي ::.

  string connectionString;
	SqlCommand command;
	public string ConnectionString
	{
		get { return connectionString; }
		// set { connectionString = value; } value from config .....
	}


	// pass sql string as parameter
	// return dataset to separate data from interface
	public DataSet ExecuteCmdSelect(string SqlCmd)
	{

			connectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
			command = new SqlCommand();
			SqlConnection MyConnection = new SqlConnection(ConnectionString);
			//Open the Connection to the Sql Server
			MyConnection.Open();
			string SQLs = SqlCmd;
			command.CommandText = SQLs;
			command.Connection = MyConnection;
			//لتنفيذ جملة الاستعلام
			SqlDataAdapter MyDataAdapter = new SqlDataAdapter(command);
			//تحمل البيانات ،كما لاحظت اننا عرفنا DS من نوع داتا ست .. لكي يحمل البيانات 
			//المرجعه من خلال MyDataAdapter 
			DataSet DS = new DataSet();
			//بعد ذلك نقوم بعملية تعبئة الداتا ست من خلال الامر 
			MyDataAdapter.Fill(DS);
			//نقوم بأغلاق او تهيئة MyDataAdapter اي نجعله خالي من كل شيء فارغ بهذا 
			//الامر
			MyDataAdapter.Dispose();
			MyConnection.Close();
			return DS;

		}

وفي الاستعلام فقط اشتق كائن بهذه الطريقة .::

		 SqlCalss Obj = new SqlCalss();
		GridView1.DataSource = Obj.ExecuteCmdSelect("select * From News");
		GridView1.DataBind();

فمالعمل بارك الله فيكم :(

علماً بأن المفتاح في Web.config بالشكل التالي :.

<appSettings>
	<add key="ConnectionString" value="data source=localhost;initial catalog =Db;user id='cr';password='123';"/>
  </appSettings>

إن شاء الله اني وضعت كل شيء يفيدك استاذي الفاضل ..

وفقك الله لكل خير ..

بالانتظار ..

#6

up :(

#7

UP

للأهمية القصوى يا أخوان :( ...

#8
يوفي VIP كتب:
السلام عليكم ورحمة الله ..

كيف حالكم اخواني الكرام ان شاء الله بخير ...

سؤالي بسيط ان شاء الله اخواني الكرام ..

اضفت GridView وقمت بعمل الربط من خلال كود برمجي ..

أريد ان اضيف خيار الحذف ( Delete ) برمجياً يا أخوان ...

انا عرفت اضيف كلمة Delete ولكن لا اعرف كيف اكتب بداخله أي امر ّ!!

وفقكم الله لكل خير ..

عليكم السلام ورحمة الله وبركاته

تفضل أخي الكريم

في حدث الـGridView1_RowDeleting اكتب

		SQLStr = "delete from Categories where CategoriesID=" & GridView1.Rows(e.RowIndex).Cells(0).Text & ""

باعتبار أن العمود الأول هو الذي يحمل رقم القسم .

تم تعديل هذه المشاركة بواسطة المتميز في 21 ديسمبر 2007 في 18:35

460.gif

#9

حدد الخاصية DataKeyNames للجريد فيو كي تستطيع التعرف على مفتاح السجل الذي يجري عليه الحذف:

<asp:GridView ID="GridView1" DataKeyNames="CategoriesID"

اضف عمود الحذف:

<asp:CommandField ShowDeleteButton="True" />

الان من خلال الحدث GridView1_RowDeleting ستحصل على مفتاح السجل

SQLStr = "delete from Categories where CategoriesID=" + e.Keys[0].ToString();

تم تعديل هذه المشاركة بواسطة madani في 24 ديسمبر 2007 في 12:08

#10

هذا مثال باستخدام قاعده البيانات northwind

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
			CellPadding="3" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1"
			GridLines="Horizontal" ShowFooter="True" OnRowCommand="GridView1_RowCommand" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px">
			<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
			<Columns>
				<asp:TemplateField HeaderText="Select">
					<EditItemTemplate>
						<asp:CheckBox ID="CheckBox1" runat="server" />
					</EditItemTemplate>
					<HeaderTemplate>
						<asp:CheckBox ID="cbxAll" runat="server" AutoPostBack="True" OnCheckedChanged="cbxAll_CheckedChanged" />
					</HeaderTemplate>
					<ItemTemplate>
						<asp:CheckBox ID="CheckBox1" runat="server" />
					</ItemTemplate>
				</asp:TemplateField>
				<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False"
					ReadOnly="True" SortExpression="EmployeeID" />
				<asp:TemplateField HeaderText="LastName" SortExpression="LastName">
					<EditItemTemplate>
						<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox>
					</EditItemTemplate>
					<FooterTemplate>
						<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
					</FooterTemplate>
					<ItemTemplate>
						<asp:Label ID="Label2" runat="server" Text='<%# Bind("LastName") %>'></asp:Label>
					</ItemTemplate>
				</asp:TemplateField>
				<asp:TemplateField HeaderText="City" SortExpression="City">
					<EditItemTemplate>
						<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("City") %>'>
							<asp:ListItem  Value="">Select ...</asp:ListItem>
							<asp:ListItem>Cairo</asp:ListItem>
							<asp:ListItem>Alex</asp:ListItem>
							<asp:ListItem>Tanta</asp:ListItem>
						</asp:DropDownList>
					</EditItemTemplate>
					<FooterTemplate>
						<asp:DropDownList ID="DDLCity" runat="server" SelectedValue='<%# Bind("City") %>'>
							<asp:ListItem Selected="True">Select ...</asp:ListItem>
							<asp:ListItem>Cairo</asp:ListItem>
							<asp:ListItem>Alex</asp:ListItem>
							<asp:ListItem>Tanta</asp:ListItem>
						</asp:DropDownList>
						                        
						                 
					</FooterTemplate>
					<ItemTemplate>
						<asp:Label ID="Label1" runat="server" Text='<%# Bind("City") %>'></asp:Label>
					</ItemTemplate>
				</asp:TemplateField>
				<asp:TemplateField ShowHeader="False">
					<EditItemTemplate>
						<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
							Text="Update"></asp:LinkButton>
						<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
							Text="Cancel"></asp:LinkButton>
					</EditItemTemplate>
					<FooterTemplate>
						<asp:LinkButton ID="LinkButton3" runat="server" CommandName="Save">Save</asp:LinkButton>
					</FooterTemplate>
					<ItemTemplate>
						<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
							Text="Edit"></asp:LinkButton>
						<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete"
							Text="Delete"></asp:LinkButton>
					</ItemTemplate>
				</asp:TemplateField>
			</Columns>
			<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
			<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
			<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
			<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
			<AlternatingRowStyle BackColor="#F7F7F7" />
			<EmptyDataTemplate>
				There is no data to display
			</EmptyDataTemplate>
		</asp:GridView>
		<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TaskConnectionString %>"
			DeleteCommand="DELETE FROM [Employees] WHERE [EmployeeID] = @EmployeeID" InsertCommand="INSERT INTO [Employees] ([LastName], [City]) VALUES (@LastName, @City)"
			SelectCommand="SELECT * FROM [Employees]" UpdateCommand="UPDATE [Employees] SET [LastName] = @LastName, [City] = @City WHERE [EmployeeID] = @EmployeeID" >
			<DeleteParameters>
				<asp:Parameter Name="EmployeeID" Type="Int32" />
			</DeleteParameters>
			<UpdateParameters>
				<asp:Parameter Name="LastName" Type="String" />
				<asp:Parameter Name="City" Type="String" />
				<asp:Parameter Name="EmployeeID" Type="Int32" />
			</UpdateParameters>
			<InsertParameters>
				<asp:Parameter Name="LastName" Type="String" />
				<asp:Parameter Name="City" Type="String" />
			</InsertParameters>
		</asp:SqlDataSource>
		<asp:LinkButton ID="LinkButton2" runat="server" OnClick="LinkButton2_Click">Add New Row</asp:LinkButton> 
		<br />
		<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Delete Selected"
			Width="152px" />

protected void Page_Load(object sender, EventArgs e)
	{
		GridView1.FooterRow.Visible = false;

		//LinkButton1.Visible = false;

			//CheckBox checkboxAll = (CheckBox)GridView1.HeaderRow.FindControl("cbxAll");

			//if (checkboxAll.Checked == true)
			//{
			//	foreach (GridViewRow row in GridView1.Rows)
			//	{
			//		CheckBox checkbox = (CheckBox)row.FindControl("CheckBox1");
			//		checkbox.Checked = true;
			//	}
			//}
			//else
			//{
			//	foreach (GridViewRow row in GridView1.Rows)
			//	{
			//		CheckBox checkbox = (CheckBox)row.FindControl("CheckBox1");
			//		checkbox.Checked = false;
			//	}
			//}


	}


	protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
	{
		if (e.CommandName == "Save")
		{
		//	SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TaskConnectionString"].ConnectionString);
		//	SqlCommand command = new SqlCommand();
		//	command.Connection = connection;
		//	command.CommandText = "INSERT INTO [Employees] ([LastName], [City]) VALUES (@LastName, @City)";
		//	connection.Open();
		//	command.Parameters.Add("@LastName",SqlDbType.NVarChar,50).Value=((TextBox)GridView1.FooterRow.FindControl("txtLastName")).Text.ToString();
		//	command.Parameters.Add("@City", SqlDbType.NVarChar, 50).Value = ((DropDownList)GridView1.FooterRow.FindControl("DropDownList1")).SelectedValue;

		//	int rowaffected = command.ExecuteNonQuery();
		//	connection.Close();

			try
			{
				TextBox txtName = (TextBox)GridView1.FooterRow.FindControl("txtLastName");
				DropDownList DDLCity = (DropDownList)GridView1.FooterRow.FindControl("DDLCity");

				SqlDataSource1.InsertParameters["LastName"].DefaultValue = txtName.Text;
				SqlDataSource1.InsertParameters["City"].DefaultValue = DDLCity.SelectedValue;
				SqlDataSource1.Insert();
			}
			catch (Exception ex)
			{

			}
		}

	}

	//-- Add new Row LinkButton
	protected void LinkButton2_Click(object sender, EventArgs e)
	{
		//if (GridView1.Rows.Count <= 0)
		//{
		//	//LinkButton2.Visible = false;
		//	//Button1.Visible = false;
		//}
		//else
		//{
			GridView1.FooterRow.Visible = true;
		//}
	}

	// Delete Selected CheckBox button
	protected void Button1_Click(object sender, EventArgs e)
	{
	   // GridView1.FooterRow.Visible = false;

		foreach (GridViewRow row in GridView1.Rows)
		{
			CheckBox checkbox = (CheckBox)row.FindControl("CheckBox1");

			if (checkbox.Checked == true)
			{
				int EmployeeID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);

				SqlDataSource1.DeleteParameters["EmployeeID"].DefaultValue = EmployeeID.ToString();
				SqlDataSource1.Delete();

			}
		}

	}

	//-- when we check the CheckBox in Header automatically checks all Checkbox in Gridview
	protected void cbxAll_CheckedChanged(object sender, EventArgs e)
	{
		CheckBox checkboxAll = (CheckBox)GridView1.HeaderRow.FindControl("cbxAll");

		if (checkboxAll.Checked == true)
		{
			foreach (GridViewRow row in GridView1.Rows)
			{
				CheckBox checkbox = (CheckBox)row.FindControl("CheckBox1");
				checkbox.Checked = true;
			}
		}
		else
		{
			foreach (GridViewRow row in GridView1.Rows)
			{
				CheckBox checkbox = (CheckBox)row.FindControl("CheckBox1");
				checkbox.Checked = false;
			}
		}


	}

ارجو ان اكون قد افادتك

Yasser Zaid

Web Developer

My Blog

Telecome Egypt

هذا الموضوع مغلق.

مواضيع مشابهة